当我编译这段代码时:
std::tuple<int, int> array[] = {std::make_tuple(1, 2), std::make_tuple(1, 2),
std::make_tuple(1, 2), std::make_tuple(1, 2)};
for (auto[a, b] : array) {
printf("%u %u", a, b);
}
if (auto[a, b] = std::forward_as_tuple(1, 2); b != 0xff) {
printf("%u %u", a, b);
}
while (auto[a, b] = std::make_tuple(1, 2); b != 0xff) {
printf("%u %u", a, b);
}
与:
clang++ -std=c++1z
我收到以下错误:
main2.cpp:76:14: error: decomposition declaration not permitted in this context
while (auto[a, b] = std::make_tuple(1, 2); b != 0xff) {
^~~~~~
main2.cpp:76:46: error: use of undeclared identifier 'b'
while (auto[a, b] = std::make_tuple(1, 2); b != 0xff) {
^
2 errors generated.
为什么 auto[a, b] = std::forward_as_tuple(1, 2); b != 0xff
在 if
中支持但在 while
中不支持?是有一些技术原因还是“事情就是这样”的原因?
最佳答案
根据最新的 C++ 标准草案,while
循环实际上没有 if
那样的可选 init-statement
和 switch
在 C++17 中获得。
正式语法是:
while ( condition ) statement
总之,结构化绑定(bind)不是这里的问题。检查this部分草案供引用。
关于for vs if vs while 中的 C++17 结构化绑定(bind)声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44730713/