Code Snippets
/

auto and decltype Idioms

auto and decltype Idioms

`auto` lets the compiler deduce a variable's type from its initialiser; `decltype` extracts the type of an expression for use in declarations. Together they make modern C++ much less verbose, especially for iterators, lambdas, and templates. This snippet covers the basic deduction rules, the difference between `auto` and `auto&`, and when to reach for `decltype` over `auto`.

C++
Easy
3 snippets
cpp-auto-keyword
type-system
cpp-templates

411 views

8

#include <iostream>
#include <vector>
#include <map>
#include <string>

int main() {
    std::vector<int> v = {1, 2, 3, 4};
    std::map<std::string, int> m = {{"ada", 36}, {"linus", 54}};

    // Without auto: std::vector<int>::iterator it = v.begin();
    auto it = v.begin();
    std::cout << "first=" << *it << "\n";

    // Without auto: std::map<std::string, int>::const_iterator mi = m.cbegin();
    auto mi = m.cbegin();
    std::cout << mi->first << "=" << mi->second << "\n";

    // auto deduces value semantics, dropping const and references.
    const int& ref = v[0];
    auto a = ref; // a is plain int (copy of ref)
    a = 99;       // does not affect v[0]
    std::cout << "v[0]=" << v[0] << " a=" << a << "\n";
    return 0;
}

auto deduces the type the way a function template parameter would: it strips top-level const and references by default. So auto a = ref declares a as a fresh int copy, regardless of whether the initialiser is const int& or just int. Use auto to escape the verbose iterator types in the standard library; the alternative for std::map<std::string, int>::const_iterator is unreadable. Keep types explicit at API boundaries (function signatures, public class fields) where the type IS the documentation.