我有点困惑为什么在某些情况下使用逗号运算符的 decltype
会返回引用类型。
例如,在这段代码中:
int i = 101;
decltype(1, i) var = i;
var = 20;
printf("%d\n", i); // will print 20
在这里,var 是 int& 而不是 int,但是如果我将第二行替换为:
decltype(i) var = i;
它将返回 int!
谁能解释一下?
最佳答案
decltype
是特殊情况,用于未加括号的 id-expression 以给出实体的类型,没有引用限定 [dcl.type.simple]:
4 - The type denoted by
decltype(e)
is defined as follows:
— ife
is an unparenthesized id-expression or an unparenthesized class member access (5.2.5),decltype(e)
is the type of the entity named bye
. [...]
— otherwise, ife
is an lvalue,decltype(e)
isT&
, whereT
is the type ofe
; [...]
通过提供逗号表达式,您将禁用这种特殊情况,就像括号一样:
decltype(i) // int
decltype((i)) // int&
decltype(1, i) // int&
(i)
和1, i
是左值表达式,所以它们的decltype
是引用类型。
关于c++11 decltype 返回引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25186601/