当传递函数指针时,是否应该转发关于非例外性的知识?
Is knowledge about noexcept-ness supposed to be forwarded when passing around a function pointer?
我已经编写了以下代码来测试跨函数调用的noexcept
传播,并且似乎它不像我想象的那样工作。在GCC 4.7.2中,只有直接或作为模板专门化参数传递时,才能有效地测试函数是否为noexcept
;但是当作为参数传递给模板函数时,或者作为普通函数的函数指针时,不能——即使该函数声明其形式形参为noexcept
。下面是代码:
#include <iostream>
#define test(f)
std::cout << __func__ << ": " #f " is "
<< (noexcept(f()) ? "" : "not ")
<< "noexceptn";
template <void(*f)()>
static inline void test0() {
test(f);
}
template <typename F>
static inline void test1(F f) {
test(f);
}
static inline void test2(void(*f)()) {
test(f);
}
static inline void test3(void(*f)()noexcept) {
test(f);
}
void f1() {}
void f2() noexcept {}
int main() {
test(f1);
test(f2);
test0<f1>();
test0<f2>();
test1(f1);
test1(f2);
test2(f1);
test2(f2);
test3(f1);
test3(f2);
return 0;
}
输出:
<>之前主:f1不是不例外Main: f2是不例外的Test0:不是noexceptTest0:不例外Test1:不是noexceptTest1:不是noexceptTest2:不是noexceptTest2:不是noexceptTest3:不是不例外Test3:不是不例外之前为什么noexcept
在其他情况下不传播?在test1
的情况下,整个函数被"实例化"为F
的适当类型,此时编译器肯定知道F是否为noexcept
函数。当noexcept
ness声明完全被忽略时,为什么可以按照我写的方式写test3
?
标准对此有具体的规定吗?
c++ 11标准第15.4.13节声明"异常规范不被认为是函数类型的一部分"。
在c++ 17中,noexcept
最终被添加到类型系统中。指向非noexcept
函数的指针不能隐式转换为指向noexcept
函数的指针。(但反过来也是允许的)。
clang 3.9.0 with -std=c++1z
, g++ 7.0 with -std=c++17
,拒绝test3(f1);
行
相关文章:
- 如何确定我已使用非编码文件到达 EOF?
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 将公共但非静态的成员函数与ALGLIB集成
- 不同翻译单元中不可重载的非内联函数定义
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 初始化具有非默认构造函数的std::数组项的更好方法
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- 如何在C++中使用非静态成员函数作为回调函数
- 数组中最大的非重复元素
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 有没有可能有一个只有ADL才能找到的非好友功能
- 为x86而非x64编译时出错
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 隐式常量/非常量运算符布尔
- 非常量变量只读位置的赋值
- C++中的动态对象与非动态对象
- 如何从非远外例外减少调试开销
- 当传递函数指针时,是否应该转发关于非例外性的知识?