小编bur*_*ood的帖子

C++:条件表达式中的始终抛出函数

条件表达式允许 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 …
Run Code Online (Sandbox Code Playgroud)

c++ conditional-operator

3
推荐指数
1
解决办法
96
查看次数

标签 统计

c++ ×1

conditional-operator ×1