[英]Why does structured binding not work as expected on struct?
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
为什么结构化绑定在struct上不能按预期工作?
这是一个已知的错误。 请参阅https://bugs.llvm.org/show_bug.cgi?id=33236 。
基本上,问题是,编写的C ++ 17标准规定结构化绑定声明将T
视为类似元组的类型,并且只要定义了std::tuple_size<T>
就使用std::tuple_size<T>::value
; 但它还指定标准库为所有const类型T
定义std::tuple_size<T>
。
这意味着,当编译const auto&[r3, r4] = x;
,Clang查找std::tuple_size<const X>
,并在标准库中找到该定义(由MSVC提供)。 由于成功找到了std::tuple_size<const X>
的定义,Clang尝试使用“类似元组”的绑定协议,它肯定会失败: const X
就像一个元组!
来自MSVC STL维护者的建议( 来源 ):
解决方法:不要在struct上使用const。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.