c++11 decltype 返回引用类型

标签 c++ c++11 decltype

我有点困惑为什么在某些情况下使用逗号运算符的 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:
— if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e. [...]
— otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e; [...]

通过提供逗号表达式,您将禁用这种特殊情况,就像括号一样:

decltype(i)    // int
decltype((i))  // int&
decltype(1, i) // int&

(i)1, i 是左值表达式,所以它们的decltype 是引用类型。

关于c++11 decltype 返回引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25186601/

相关文章:

C++11:lambda 捕获以什么顺序被破坏?

c++ - 并发写入 vector<bool>

C++:可以使用 decltype 从我的头文件中复制类型吗?

c++ - 转发 decltype 检测 - C++ 11

c++ - 从唯一指针到基类的派生类的 decltype

c++ - 我的机器上的 std::promise 是否损坏(使用 g++-mp)?

c++ - boost 正则表达式排除一个字符

c++ - 错误 : non-aggregate type 'Circle' cannot be initialized with an initializer list

c++ - 在 C++ 项目中进行 TDD 是否可能/足够高效?

c++ - 将多态 unique_ptr 作为参数传递时发生内存泄漏