c++ - 我可以在 typedef 函数签名中放置 throw 声明吗?

标签 c++

是否可以声明一个包含抛出规范的函数指针?例如,我有这个功能:

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/

相关文章:

c++ - 在私有(private)函数中锁定/解锁互斥锁

c++ - 使用 DX 缩放对象

c++ - sprintf 错误 "variable may be unsafe"(C4996)... 替代方案?

c++ - libuv + C++ 段错误

c++ - 基于套接字的事件循环

c++ - 这行代码是做什么的?玩家 = (玩家 % 2) ? 1 : 2;

c++ - 在 C++ 中实现随机 oracle(输出在范围内是随机的,但相同输入的输出相同)

c++ - 如何在vscode中构建、运行和删除可执行文件和虚拟文件

c++ - 使用 OpenSSL 构建 QT 期间出错

c++ - 使用原始套接字未检测到 UDP 数据包