使用三元运算符引发

Throwing with the ternary operator

本文关键字:三元 运算符      更新时间:2023-10-16

编译:

struct A{};
struct B{};
int main(){
  if(true)
    throw A();
  else
    throw B();  
}

,但

struct A{};
struct B{};
int main(){
  throw( true ?  A() : B() );
}

不会。

我可以用三元运算符抛出吗?

AB是不同的、不兼容的类型,因此表达式true ? A() : B()类型不正确(必须是AB)。

三元运算符需要在两个路径上具有相同的类型(或可转换为相同类型的东西),否则编译器无法推断类型安全性。

如果条件运算符有结果,则类型需要以某种方式兼容。如果类型不兼容,您仍然可以从三元运算符抛出,不过:

condition? throw A(): throw B();

尽管我尝试过的所有编译器都编译了上述语句,但这似乎是非法的:根据5.16[expr.cond]第2段,第一个项目符号"第二个或第三个操作数(但不是两者)是一个(可能带括号的)抛出表达式(15.1);…"

condition? (throw A()), true: throw B()