簡體   English   中英

for vs if vs while中的C ++ 17結構化綁定聲明

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

當我編譯這段代碼時:

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 auto[a, b] = std::forward_as_tuple(1, 2); b != 0xff if在一段while 是否存在某種技術原因,還是“這就是事實”的原因?

根據最新的C ++標准草案, while循環實際上沒有可選的init-statement ,它是ifswitch在C ++ 17中獲得的。

正式語法為:

while ( condition ) statement

總之,結構化綁定不是這里的問題。 檢查草稿的部分以供參考。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM