如何修复 MSVC 中与 'for' 循环内的匿名结构声明相关的编译错误?

How to fix compilation errors in MSVC related to declaration of anonymous struct inside a 'for' loop?

我们可以在 for 循环中声明匿名 structbelow (g++):

for(struct { bool OK = true; } s; s.OK; s.OK = false)
  std::cout << "Hello, world!\n";

但是,此代码导致 MSVC 中的编译错误为:

source_file.cpp(7): error C2332: 'struct': missing tag name
source_file.cpp(7): error C2062: type 'bool' unexpected
source_file.cpp(7): error C4430: missing type specifier - int assumed.
Note: C++ does not support default-int

如何解决?


版本

C:\Program Files (x86)\Microsoft Visual Studio17\Community>cl
Microsoft (R) C/C++ Optimizing Compiler Version 19.14.26430 for x86
Copyright (C) Microsoft Corporation. All rights reserved.

请注意,MSVC 19.14 显示 error C2062: type 'bool' unexpected,即使对于命名结构 S,如本例所示:

  for(struct S { bool OK = true; } s; s.OK; s.OK = false)
    std::cout << "Hello, world!\n";

演示:https://godbolt.org/z/Ev1GMGMYd

我认为最简单的解决方法是升级到下一个编译器版本 MSVC 19.15,这两个问题都得到了修复。演示:https://godbolt.org/z/W14dvW5eW