c++ - noexcept 运算符编译时检查
问题描述
在下面的代码中,我尝试对函数使用条件异常规范,但编译失败,尽管如果在函数外部使用它就可以了。
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());
}
问题是如何在不更改函数原型以有条件地指定的情况下检查函数是否抛出noexcept
?
我无法更改函数原型,因为关键是检查函数是否应该返回 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 说明符需要一个可转换为 的表达式bool
,而may_throw()
返回void
且不能转换为bool
。
您应该应用noexcept 运算符并将may_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.