c++ - 三元运算符中为什么不能使用braced-init-list?

标签 c++ visual-c++ c++11 initialization ternary-operator

我的编译器是最新的 VC++ 2013 RC。

int f(bool b)
{
    return {}; // OK
    return b ?  1  : { }; // C2059: syntax error : '{'
    return b ?  1  : {0}; // C2059: syntax error : '{'
    return b ? {1} : {0}; // C2059: syntax error : '{'
}

为什么三元运算符中不能使用braced-init-list?

这种行为是否被 C++ 标准定义为格式错误,还是只是 VC++ 编译器的错误?

最佳答案

嗯,这就是标准对括号初始化列表 (8.5.3.1) 的描述:

List-initialization can be used

  • as the initializer in a variable definition (8.5)
  • as the initializer in a new expression (5.3.4)
  • in a return statement (6.6.3)
  • as a function argument (5.2.2)
  • as a subscript (5.2.1)
  • as an argument to a constructor invocation (8.5, 5.2.3)
  • as an initializer for a non-static data member (9.2)
  • in a mem-initializer (12.6.2)
  • on the right-hand side of an assignment (5.17)

由于这里没有提到条件运算符,我猜你的编译器是对的。另请注意,条件运算符需要 : (5.16) 两侧的表达式,据我了解,大括号初始化器不是表达式。

关于c++ - 三元运算符中为什么不能使用braced-init-list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18843017/

相关文章:

html - C++:如何递归/迭代搜索 HTML 文件(使用 Boost C++)?

c++ - 寻找二叉搜索树中的最小元素——进入死循环

c++ - C++ 中的隐式变量初始化

c++ - 具有抑制 move 构造函数/分配的类型如何仍被视为可 move 的?

c++ - 读取 cmd 生成的文件,结果出现 3 个奇怪的符号

c++ - 如何修复错误 2298 和 2563

c++ - 在 Visual Studio 中使用 __asm 返回 float 堆栈中的 double 值

visual-c++ - VC++中DLL库中的dllmain

c++ - 类模板 : Prevent assignment of <other> type

C++。如何使用 sregex_token_iterator 检测匹配和不匹配的部分?