17
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 (on Windows) 的错误信息:

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

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

4

1 回答 1

11

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

基本上,问题在于,所编写的 C++17 标准指定结构化绑定声明视为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 尝试使用“类元组”绑定协议,果然失败了:const X不像元组!

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

解决方法:不要在结构上使用 const。

于 2018-12-11T13:01:41.760 回答