条件表达式允许抛出表达式作为操作数。我想要一个条件表达式,其中一个操作数是一个总是抛出的函数,但看起来这是不可能的。
#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
}
我也尝试过内联 foo,但它也无法编译。错误是一样的:
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
有没有办法在表达式中调用该函数?我的用例是从一种语言到 C++ 的转换器,而其他语言支持案例表达式,如果表达式中没有命中任何案例,则会抛出异常。我尝试支持的大小写表达式与此类似:
http://zvon.org/other/haskell/Outputsyntax/caseQexpressions_reference.html
最佳答案
您可以像这样使用逗号运算符:
int a = true ? 1 : (throw std::exception(), 0);
int b = true ? 1 : (foo(), 0);
查看它在 godbolt.org 上的工作.
关于C++:条件表达式中的 Always-Throw 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72537141/