我的编译器是最新的 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/