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

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

与:

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 != 0xffif 中支持但在 while 中不支持?是有一些技术原因还是“事情就是这样”的原因?

最佳答案

根据最新的 C++ 标准草案,while 循环实际上没有 if 那样的可选 init-statementswitch 在 C++17 中获得。

正式语法是:

while ( condition ) statement

总之,结构化绑定(bind)不是这里的问题。检查this部分草案供引用。

关于for vs if vs while 中的 C++17 结构化绑定(bind)声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44730713/

相关文章:

c++ - 如何将 BOOST_FOREACH 与仅支持 const_iterator 的容器一起使用?

c++ - 如何根据输入中定义的 "external"int 在结构中定义数组大小

c++ - 从函数类型中剥离所有限定符

c++ - 在 for 循环中使用 auto 和 decltype(vector.size()) 处理字符串 vector

c++ - 对具有不同值的图像的每个 channel 进行归一化的快速有效方法

c++ - 如何替换动态异常规范 : throw(. ..)

c++ - 为什么我不应该将 #include 语句放在 .h 文件中?

c++ - 提升图形库 : Is there a neat algorithm built into BGL for community detection?

c++ - 帮助 C++ 化这个 C 风格的代码

c++ - 对 N 个不同大小的数组的每个元素应用相同的函数