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/