Conditional expressions allow throw expressions as operands. I would like to have a conditional expression where one of the operands is an always-throw function, however it appears that this is not possible.
#include<exception>
[[ noreturn ]] void foo() {
throw std::exception();
}
int main() {
int a = true ? 1 : throw std::exception();
int b = true ? 1 : foo(); // This will not compile
}
I've tried inlining foo as well, but it wouldn't compile either. The error is the same:
test.cc: In function 'int main()':
test.cc:9:18: error: third operand to the conditional operator is of type 'void', but the second operand is neither a throw-expression nor of type 'void'
int b = true ? 1 : foo(); // This will not compile
Is there a way to achieve calling that function inside the expression? My use case is a transpiler from a language to C and that other language supports case expressions where if no case is hit in the expression, an exception is thrown. Case expressions I'm trying to support are similar to this:
http://zvon.org/other/haskell/Outputsyntax/caseQexpressions_reference.html
CodePudding user response:
You can use the comma operator like so:
int a = true ? 1 : (throw std::exception(), 0);
int b = true ? 1 : (foo(), 0);
See it working on godbolt.org.