This compiles:
struct A{};
struct B{};
int main(){
if(true)
throw A();
else
throw B();
}
, but
struct A{};
struct B{};
int main(){
throw( true ? A() : B() );
}
won't.
Can I throw with the ternary operator?
This compiles:
struct A{};
struct B{};
int main(){
if(true)
throw A();
else
throw B();
}
, but
struct A{};
struct B{};
int main(){
throw( true ? A() : B() );
}
won't.
Can I throw with the ternary operator?
A
and B
are different, incompatible types, so the expression true ? A() : B()
is ill-typed (it'd have to be either an A
or a B
).
Ternary operator needs to have the same type(or something convertible to the same type) on both paths otherwise the compiler can't reason about type safety.
If there is a result from the conditional operator, the types needs to be somehow compatible. If the types are not compatible, you can still throw from a ternary operator, though:
condition? throw A(): throw B();
Although all compilers I tried do compile the above statement, it seems to be illegal: according to 5.16 [expr.cond] paragraph 2, first bullet "The second or the third operand (but not both) is a (possibly parenthesized) throw-expression (15.1); ...". To counter that constraint it is possible to use something like
condition? (throw A()), true: throw B()