C++:条件表达式中的 Always-Throw 函数

标签 c++ conditional-operator

条件表达式允许抛出表达式作为操作数。我想要一个条件表达式,其中一个操作数是一个总是抛出的函数,但看起来这是不可能的。

#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/

相关文章:

c++ - 什么时候从函数的参数化中省略 const 是安全的?

c++ - 使用成员函数求解方程 C++

C++ Typedef 签名

java - 不是一个声明。为什么不?

Python 正则表达式 : changing conditional operators

perl - 在 Perl 中使用三元条件运算符有更短的方法吗?

c++ - std::vector 和动态分配数组有什么区别?

c++ - 聚焦时为 QSpinBox 设置边框

c# - 如何在C#中使用三元运算符

java - if 与条件条件相比的速度