是否可以声明一个包含抛出规范的函数指针?例如,我有这个功能:
void without_throw() throw() {
}
并想创建一个接受它作为参数的函数,完成 throw()
部分。我试过将它添加到 typedef
中,但这似乎不起作用:
typedef void (*without)() throw();
GCC 给我错误 error: ‘without’ declared with an exception specification
。
最佳答案
你不能输入定义。标准中明确不允许这样做。 (将其替换为 noexcept
也无济于事,同样的问题。)
引用 C++11 草案 n3290(§15.4/2 异常规范)
An exception-specification shall appear only on a function declarator for a function type, pointer to function type, reference to function type, or pointer to member function type that is the top-level type of a declaration or definition, or on such a type appearing as a parameter or return type in a function declarator. An exception-specification shall not appear in a typedef declaration or alias-declaration. [ Example:
void f() throw(int); // OK void (*fp)() throw (int); // OK void g(void pfa() throw(int)); // OK typedef int (*pf)() throw(int); // ill-formed
– end example]
第二个例子允许你做这样的事情:
void foo() throw() {}
void bar() {}
int main()
{
void (*fa)() throw() = foo;
void (*fb)() throw() = bar; // error, does not compile
}
关于c++ - 我可以在 typedef 函数签名中放置 throw 声明吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26838452/