Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the C++11 standard guarantee "n2 is int&" by "auto n2 = const_cast<int&>(n);"?

const int n = 0;
auto& n1 = const_cast<int&>(n);
auto n2 = const_cast<int&>(n);

Does the C++11 standard guarantee n2 is int& by auto n2 = const_cast<int&>(n);?

Must I use auto& n1 = const_cast<int&>(n); instead of auto n2 = const_cast<int&>(n);?

Are the two ways completely equivalent to each other as per the C++11 standard?

like image 888
xmllmx Avatar asked Dec 23 '22 23:12

xmllmx


1 Answers

auto uses the same rules as regular function template argument deduction, which never deduces a reference.

C++14 decltype(auto), on the other hand, can deduce a reference here. As well as C++11 auto&&.

const int n = 0;
auto a = const_cast<int&>(n);           // a is int
decltype(auto) b = const_cast<int&>(n); // b is int&
auto&& c = const_cast<int&>(n);         // c is int&
like image 80
Maxim Egorushkin Avatar answered Mar 02 '23 00:03

Maxim Egorushkin