Irf*_*rfy 7 c++ noexcept c++11
我编写了以下代码来测试noexcept
函数调用之间的传播,它似乎不像我想象的那样工作.在GCC 4.7.2中,可以有效地测试一个函数,noexcept
不仅仅是直接或作为模板特化参数传递; 但不是作为参数传递给模板化函数,或作为函数指针传递给普通函数 - 即使该函数声明其形式参数为noexcept
.这是代码:
#include <iostream>
#define test(f) \
std::cout << __func__ << ": " #f " is " \
<< (noexcept(f()) ? "" : "not ") \
<< "noexcept\n";
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;
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
main: f1 is not noexcept main: f2 is noexcept test0: f is not noexcept test0: f is noexcept test1: f is not noexcept test1: f is not noexcept test2: f is not noexcept test2: f is not noexcept test3: f is not noexcept test3: f is not noexcept
为什么noexcept
在其他情况下不会传播?在test1
整个函数被"实例化"的情况下,具有适当的类型F
,编译器当然肯定知道F是否是noexcept
函数.test3
当noexcept
ness声明被完全忽略时,为什么可以写出我写它的方式?
标准是否必须说明具体的内容?
在C++17中,noexcept
最终被添加到类型系统中。指向非noexcept
函数的指针不能隐式转换为指向noexcept
函数的指针。(但反过来也是允许的)。
clang 3.9.0-std=c++1z
和 g++ 7.0 都-std=c++17
拒绝该行test3(f1);
。