使用三元运算符引发
Throwing with the ternary operator
编译:
struct A{};
struct B{};
int main(){
if(true)
throw A();
else
throw B();
}
,但
struct A{};
struct B{};
int main(){
throw( true ? A() : B() );
}
不会。
我可以用三元运算符抛出吗?
A
和B
是不同的、不兼容的类型,因此表达式true ? A() : B()
类型不正确(必须是A
或B
)。
三元运算符需要在两个路径上具有相同的类型(或可转换为相同类型的东西),否则编译器无法推断类型安全性。
如果条件运算符有结果,则类型需要以某种方式兼容。如果类型不兼容,您仍然可以从三元运算符抛出,不过:
condition? throw A(): throw B();
尽管我尝试过的所有编译器都编译了上述语句,但这似乎是非法的:根据5.16[expr.cond]第2段,第一个项目符号"第二个或第三个操作数(但不是两者)是一个(可能带括号的)抛出表达式(15.1);…"
condition? (throw A()), true: throw B()
相关文章:
- 三元运算符和 if constexpr
- 在 c++ 中三元运算符中不允许继续(关键字)吗?
- 三元运算符在返回语句中给出意外的结果
- 递归中三元运算符的奇怪行为
- 错误:三元运算符无法在对象中正常工作"cout"
- 是否允许三元运算符在C++中计算两个操作数?
- 有条件地选择带有 decltype() 和三元运算符的类型
- 三元运算符在C++中的意外行为
- 有没有办法将 for 循环结果返回到像三元运算符这样的函数中?
- 变量值,在三元运算符之后
- 是否可以在C++中使用三元运算符在 if 语句中选择比较运算符?
- c++中的增量和三元运算符优先级
- C++中三元运算符的意外行为
- 用于返回开关的三元运算符
- 替换模板元编程中的三元运算符
- 三元运算符 '?:' 在 4.9.0 之前的 GCC 版本中推断出不正确的类型?
- 在 std::map 上使用三元运算符和 std::更大的附加参数
- "Do nothing"在三元运算符的其他部分?
- 如何确定三元运算符的返回类型?
- 无法使用三元运算符有条件地分配"istream &"?