c++ - 为什么结构化绑定(bind)在结构上不能按预期工作?

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

struct X { int a, b; };

int main()
{
    auto p = std::pair{ 1, 2 };
    const auto&[r1, r2] = p; // ok

    X x{ 1, 2 };
    const auto&[r3, r4] = x; // error
}

clang 7.0(Windows 上)的错误消息:

error : cannot decompose this type; 'std::tuple_size<const X>::value' is not a valid 
           integral constant expression

为什么结构化绑定(bind)在结构上不能按预期工作?

最佳答案

这是一个已知错误。请参阅https://bugs.llvm.org/show_bug.cgi?id=33236 .

基本上,问题是,书面的 C++17 标准指定结构化绑定(bind)声明处理 T作为类似元组的类型并使用 std::tuple_size<T>::value每当std::tuple_size<T>被定义为;但它还指定标准库定义 std::tuple_size<T>对于所有 const 类型 T .

也就是说,编译时const auto&[r3, r4] = x; , Clang 寻找 std::tuple_size<const X> ,并在标准库(由MSVC提供)中查找定义。自从std::tuple_size<const X>的定义以来成功找到后,Clang 尝试使用“类似元组”的绑定(bind)协议(protocol),结果果然失败了:const X与元组完全不同!

来自 MSVC STL 维护者 ( source ) 的建议:

Workaround: don’t use const on the struct.

关于c++ - 为什么结构化绑定(bind)在结构上不能按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53721714/

相关文章:

作为参数给出的 Bash 函数调用命令

c - C 标准库中包含什么?

c++ - 包含 Cocoa header 时出错

c++ - C/C++ 用一个值填充结构数组

git 别名现在不能说 "read: illegal option -t"

c++ - 在 C++ 中绑定(bind)多个引用的临时对象的生命周期

C++ 调用堆栈不符合标准?

c++ - 异构HashMap c++

c++ - 替换方法改变 QByteArray 的大小

带有 set -e 的 Shell 别名会使命令失败?