c++ - 为什么绑定(bind)到引用类型时 "const auto [x, y]"的行为不符合预期?

标签 c++ standards c++17 decltype structured-bindings

以下代码片段摘自 cppref :

std::tuple<int, int&> f();

auto [x, y] = f(); 
// decltype(x) is int
// decltype(y) is int&

const auto [z, w] = f();
// decltype(z) is const int
// decltype(w) is int&

我的问题在最后一行:

为什么 decltype(w) int& 而不是 const int&?

最佳答案

Jarod42回答了评论中的问题,让我在这里引用标准的相关部分,来自 [dcl.struct.bind]¹:

Given the type Ti designated by std​::​tuple_­element​::​type, variables are introduced with unique names ri of type “reference to Ti” initialized with the initializer ([dcl.init.ref]), where the reference is an lvalue reference if the initializer is an lvalue and an rvalue reference otherwise. Each vi is the name of an lvalue of type Ti that refers to the object bound to ri; the referenced type is Ti.

因此在 const auto [z, w] = f(); 中,你有 const T1T1int const T2 其中 T2int&。当 const 修改左边的内容时,这变成 int& const 并导致 int&

注意 int& const 变成 int& 只能在模板参数替换中,也就是说,这不会编译:

int n = 42;
int& const doesntWork = n; // Error: 'const' qualifiers cannot be applied to 'int&'

但确实如此:

template <class T> void f(const T t)
{
   ++t;
}

int n = 42;

f<int&>(n);

int& constint& 发生与上述相同的收缩。

¹ 感谢@cpplearner 将我指向此处的确切段落。

关于c++ - 为什么绑定(bind)到引用类型时 "const auto [x, y]"的行为不符合预期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51719992/

相关文章:

c++ - 获取在 operator new 中分配的对象类型

c++ - 如何正确使用生成的 protobuf 源?

c++ - 整数和 float 之间的加法......结果为零

c++ - C++17 会支持更简单的基于范围的 For 循环吗?

c++ - 复制变量、创建临时变量和移动语义

c++ - 是否可以以编程方式构造 std::initializer_list?

c++ - 我如何知道编译器支持哪些标准格式?

c - scanf 'maximum field width' 包含空格?

c++ - 可以使用自动占位符来推断非类型模板参数中的函数结果吗?

c++ - 使用 map 提取和重新插入的限制性规则的基本原理