gpt4 book ai didi

c++ - 如何为 noexcept 函数指针创建别名?

转载 作者:可可西里 更新时间:2023-11-01 15:48:37 24 4
gpt4 key购买 nike

我想这样做:

using function_type = void (*)(void*)noexcept;

但是我得到一个错误“类型别名中不允许异常规范”。 (Xcode 6.1 版本中的 clang)

是否有解决方法来创建带有 noexcept 说明符的别名?

我正在寻找能够按照跨平台功能的语言(而非扩展)定义的东西。

最佳答案

该标准明确禁止异常规范出现在 typedef 或别名声明中。但它也指出异常说明符可能出现在函数指针类型中。

§15.4/2 [except.spec]

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.

如果指向函数的指针确实有异常规范,则必须始终为该函数指针分配具有兼容异常规范的函数类型。

§15.4/5

... A similar restriction applies to assignment to and initialization of pointers to functions, pointers to member functions, and references to functions: the target entity shall allow at least the exceptions allowed by the source value in the assignment or initialization. ...

使用这两个,您可以以迂回的方式将 noexcept 规范获取到函数指针类型中。

void (*foo_ptr)(void *) noexcept = nullptr;
using function_type = decltype(foo_ptr);

现在,您不能将没有 noexcept(true) 规范的函数分配给 function_type 类型的函数指针。 clang will fail to compile有错误的代码

error: target exception specification is not superset of source

关于c++ - 如何为 noexcept 函数指针创建别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27489558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com