gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:32:54 25 4
gpt4 key购买 nike

当我编译这段代码时:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com