C++ 17结构化绑定声明用于vs vs if while?

oco*_*or0 0 c++ c++17

当我编译这段代码时:

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);
}
Run Code Online (Sandbox Code Playgroud)

附:

clang++ -std=c++1z
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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.
Run Code Online (Sandbox Code Playgroud)

为什么auto[a, b] = std::forward_as_tuple(1, 2); b != 0xff支持if但不支持while?是否存在一些技术原因或是"这就是它的原因"理由?

Dei*_*Dei 6

根据对C++的最新标准草案中,while循环没有实际上有一个可选init-statement的那种if,并switch获得了C++ 17.

形式语法是:

while ( condition ) statement
Run Code Online (Sandbox Code Playgroud)

总之,结构化绑定不是这里的问题.检查草案的这一部分以供参考.

  • 带有init语句的`while`循环拼写为`for` :) (4认同)
  • @Barry但它不会更新变量,不像`while`版本那样.但是我现在看到它的含义含糊不清,也许因此而被禁止. (2认同)