标准文档里面说,假如decltype的对象是一个表达式(x),那么得到的类型,假如x是int那么就是int&
不理解这个规则。做了个小实验
不理解这个规则。做了个小实验
int x = 1; decltype((x)) r = x; r = 3; cout << x << endl;
确实,x变成了3。本人的问题是”(x)”算是一个表达式(expression)吗,假如是的话,那么本人期待:
decltype((1))i = x; i = 4; cout << x << endl;
这里”1″是一个int类型的常数,那么(1)能否也是个表达式? 假如是的话,decltype((1))能否因该也返回int&。但测试结果表明,不是这样,x没有变成4
为什么上面两个实验结果不同,到底怎么样理解(x)是一个表达式?
解决方案
15
The type denoted by decltype(e) is defined as follows:
if e is an lvalue, decltype(e) is T&, where T is the type of e;
if e is an lvalue, decltype(e) is T&, where T is the type of e;
30
2) If the argument is any other expression of type T, and
a) if the value category of expression is xvalue, then decltype yields T&&;
b) if the value category of expression is lvalue, then decltype yields T&;
c) if the value category of expression is prvalue, then decltype yields T.
仔细读:http://en.cppreference.com/w/cpp/language/decltype
a) if the value category of expression is xvalue, then decltype yields T&&;
b) if the value category of expression is lvalue, then decltype yields T&;
c) if the value category of expression is prvalue, then decltype yields T.
仔细读:http://en.cppreference.com/w/cpp/language/decltype
10
额外加括号以后就是引用,标准规定的。