C++ Snippet

auto and decltype Idioms

Difficulty: Easy

`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`.

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

410 views

8

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.