使用noexcept运算符链接noexcept声明 [英] Using the noexcept operator to chain noexcept declarations
问题描述
为什么 noexcept
运算符采用表达式而不是函数签名/声明?
Why does the noexcept
operator take an expression rather than a function signature/declaration?
请考虑以下内容虚拟示例:
Consider the following dummy example:
#include <string>
void strProcessor(const std::string& str) noexcept(true) { };
struct Type{
void method1() noexcept(strProcessor("")) { //Error: Call to nonconstexpr function
strProcessor("");
}
};
由于方法1
具有
我要做的就是告诉编译器: method1
并非例外,前提是使用构造成功的字符串调用 strProcessor
时,noexcept (其中
All I want to do is tell the compiler that method1
is noexcept iff an invocation of strProcessor
with a succesfully constructed string is noexcept (which it is).
那么为什么不 noexcept(void strProcessor(const std :: string&))
?
另一个类似的虚拟示例:
Another similar dummy example:
struct Type{
Type(bool shouldThrow=false) noexcept(false) { if(shouldThrow) throw "error"; };
void method1() noexcept(true) {};
void method2() noexcept(noexcept(Type().method1())) { method1(); };
}
在这里我想说 如果在成功构造的Type实例上调用
是noexcept,除非在这种情况下调用 method1
时,method2 method2
id的地方,code> Type 甚至还不完整。
Here I'd like to say method2
is noexcept iff invoking method1
on a succesfully constructed instance of Type is noexcept (which it is in this case), but Type
isn't even complete at the point where method2
id defined.
请解释一下我对此功能的理解是否错误。
Please explain if my understanding of this feature is wrong.
推荐答案
void method1() noexcept(noexcept(strProcessor(""))) {
// Second 'noexcept' ^^^^^^^^^ ^
第一个是 noexcept
说明符 ,它指定是否 method1()
是 noexcept 。
嵌套的是 noexcept
运算符 ,它会在检查
。 strProcessor()
是否为 noexcept >
The nested one is the noexcept
operator, which checks whether strProcessor()
is noexcept when called with ""
.
第二种情况有些棘手: Type
仍然在我们要在 noexcept
内使用 method1()
的时候不完整。我来了以下解决方法,滥用了指向成员的指针:
Your second case is a bit tricky : Type
is still incomplete at the point we'd like to use method1()
inside noexcept
. I've come to the following workaround, abusing a pointer-to-member :
void method2() noexcept(noexcept(
(std::declval<Type>().*&Type::method1)()
)) {};
但是,我认为在某些情况下您只能推断 method2()
的 noexcept 规范与 method1()
的规范相同。
However, I don't think there's a case where you could only deduce method2()
's noexcept specification from that of method1()
.
这篇关于使用noexcept运算符链接noexcept声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!