🔑Go deeper — read the bookC++ Keywords by Version — Specifiers & Attributes— runnable code & full walkthrough →

cpp core · high

Type Deduction: auto & Templates

Template and auto type deduction follow the parameter's form. Step one is always the same: ignore the reference-ness of the argument. Then a by-value parameter (auto x / T param) drops top-level const/volatile and decays arrays to pointers and functions to function pointers, because it is a fresh copy. A by-reference parameter (auto& / T&) keeps cv-qualifiers and does not decay, since it aliases the original. A forwarding reference (auto&& / T&&) deduces an lvalue reference for lvalue arguments — which then collapses (int& && -> int&) — and a plain type for rvalues, preserving value category for perfect forwarding. decltype and decltype(auto) use their own, stricter rules.

🔑 Key line

Deduction always strips the argument's reference-ness first; then by-value parameters also drop top-level const and decay arrays/functions, by-reference parameters keep const and never decay, and forwarding references (auto&&/T&&) become an lvalue reference for lvalues (reference collapsing) or a plain type for rvalues.

The code

const int ci = 10;
const int& cr = ci; // cr : const int&
auto a = cr; // by value -> T = int a : int
auto& b = cr; // by ref -> T = const int b : const int&
int n = 5;
auto&& f1 = n; // lvalue -> T = int& f1 : int&
auto&& f2 = 42; // rvalue -> T = int f2 : int&&
const char name[] = "interview";
auto c = name; // by value -> array decays c : const char*
auto& d = name; // by ref -> no decay d : const char (&)[10]

What this lesson walks through

  1. 01By value: copy, so strip ref + top-level const
  2. 02By reference: const is preserved
  3. 03Forwarding reference + lvalue
  4. 04Forwarding reference + rvalue
  5. 05Gotcha: by value decays arrays
  6. 06Bind by reference to keep the array
  7. 07The deduction rules in one breath

With auto x (or a by-value template parameter T param), deduction first ignores the reference-ness of the argument, then — because you are making a fresh copy — drops the top-level const. cr is const int&, but a is just int.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Type Deduction: auto & Templates and 100+ animated C++ interview lessons.

← Previous
Type Erasure & std::function
Next →
Perfect Forwarding & Reference Collapsing