简体   繁体   English

for vs if vs while中的C ++ 17结构化绑定声明

[英]C++17 structured binding declaration in for vs if vs while?

When I compile this code: 当我编译这段代码时:

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);
}

With: 带有:

clang++ -std=c++1z

I get the following errors: 我收到以下错误:

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.

Why is auto[a, b] = std::forward_as_tuple(1, 2); b != 0xff 为什么auto[a, b] = std::forward_as_tuple(1, 2); b != 0xff auto[a, b] = std::forward_as_tuple(1, 2); b != 0xff supported in an if but not in a while ? auto[a, b] = std::forward_as_tuple(1, 2); b != 0xff if在一段while Is there some technical reason or is it a "that's just the way it is" reason? 是否存在某种技术原因,还是“这就是事实”的原因?

According to the latest draft standard for C++, the while loop does not in fact have an optional init-statement the kind that if and switch gained in C++17. 根据最新的C ++标准草案, while循环实际上没有可选的init-statement ,它是ifswitch在C ++ 17中获得的。

The formal syntax is: 正式语法为:

while ( condition ) statement

In conclusion, the structured binding is not the issue here. 总之,结构化绑定不是这里的问题。 Check this segment of the draft for reference. 检查草稿的部分以供参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM