bur*_*ood 3 c++ conditional-operator
条件表达式允许 throw 表达式作为操作数。我想要一个条件表达式,其中操作数之一是始终抛出的函数,但似乎这是不可能的。
#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
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过内联 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
Run Code Online (Sandbox Code Playgroud)
有没有办法实现在表达式内调用该函数?我的用例是从一种语言到 C++ 的转译器,而其他语言支持 case 表达式,如果表达式中没有命中 case,则会引发异常。我试图支持的案例表达式与此类似:
http://zvon.org/other/haskell/Outputsyntax/caseQexpressions_reference.html
您可以像这样使用逗号运算符:
int a = true ? 1 : (throw std::exception(), 0);
int b = true ? 1 : (foo(), 0);
Run Code Online (Sandbox Code Playgroud)
查看它在godbolt.org上的运行情况。
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |