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

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

您应该在may_throw()上应用noexcept operator并将其指定给noexcept说明符。即

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

10-13 08:25