Home > Article > Backend Development > When does `auto` in C 11 deduce a value or a reference?
In C 11, the auto keyword offers a convenient way to automatically deduce the type of a variable based on its initializer. However, there are certain нюансы to consider regarding whether auto will resolve to a value or a reference.
The rule is straightforward: it depends on how the variable is declared.
<code class="cpp">int i = 5; auto a1 = i; // value auto &a2 = i; // reference</code>
In the first case, a1 is a value because it was not declared as a reference. In the second case, a2 is a reference because it was explicitly declared as one.
Let's apply this rule to the examples you provided:
The following code demonstrates this behavior using template metaprogramming:
<code class="cpp">#include <typeinfo> #include <iostream> template< typename T > struct A { static void foo(){ std::cout << "value" << std::endl; } }; template< typename T > struct A< T&> { static void foo(){ std::cout << "reference" << std::endl; } }; float& bar() { static float t=5.5; return t; } int main() { int i = 5; int &r = i; auto a1 = i; auto a2 = r; auto a3 = bar(); A<decltype(i)>::foo(); // value A<decltype(r)>::foo(); // reference A<decltype(a1)>::foo(); // value A<decltype(a2)>::foo(); // value A<decltype(bar())>::foo(); // reference A<decltype(a3)>::foo(); // value }</code>
Output:
value reference value value reference value
This confirms that the type of auto is determined by its declaration, not by the type of its initializer.
The above is the detailed content of When does `auto` in C 11 deduce a value or a reference?. For more information, please follow other related articles on the PHP Chinese website!