gpt4 book ai didi

c++ - noexcept 运算符编译时检查

转载 作者:行者123 更新时间:2023-12-01 15:13:08 24 4
gpt4 key购买 nike

在下面的代码中,我尝试对函数使用条件异常规范,但编译失败,尽管如果在函数外部使用它就可以了。

void may_throw();

// ERROR: expression must have bool type or be convertible to bool
void check () noexcept(may_throw());

int main()
{
// works just fine!
std::cout << noexcept(may_throw());
}

问题是如何检查函数是否抛出而不更改函数原型(prototype)以有条件地指定 noexcept ?

我无法更改函数原型(prototype),因为关键是检查函数是否应该返回 true 或 false 是否抛出。

编辑

我试图取笑 noexcept但看起来它不适用于宏。
#include <iostream>

#if 0
#define ASDF(...) (void)0
#else
#define ASDF(...) throw 1
#endif

void check() noexcept(noexcept(ASDF()))
{
// wrong!
// std::cout << noexcept(noexcept(ASDF()));

// edit: it should be this, and it works.
// (tnx: StoryTeller-UnslanderMonica)
std::cout << noexcept(ASDF());
ASDF(0);
}

int main()
{
check();
}

最佳答案

给定 void check () noexcept(may_throw()); , noexcept specifier需要一个可转换为 bool 的表达式, 而 may_throw()返回 void并且无法转换为 bool .

你应该申请noexcept operatormay_throw()并将其指定为 noexcept 说明符。 IE。

// whether check is declared noexcept depends on if the expression
// may_throw() will throw any exceptions
void check () noexcept(noexcept(may_throw()));
// ^^^^^^^^ -> specifies whether check could throw exceptions
// ^^^^^^^^ -> performs a compile-time check that returns true if may_throw() is declared to not throw any exceptions, and false if not.

关于c++ - noexcept 运算符编译时检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61593166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com