[英]Strange behavior of noexcept specifier in C++14
我在 C++14 中发现了noexcept
运算符的奇怪行为。 以下代码可以通过 gcc 和 clang(使用 --std=c++14 选项)很好地编译。
// test.cpp
#include <iostream>
#include <type_traits>
#if 1
#define TESTREF(X) X&&
#else
#define TESTREF(X) X const&
#endif
template <class F, class... Args>
struct is_noexcept_callable
: public std::conditional_t<noexcept(std::declval<F>()(std::declval<Args>()...)), std::true_type, std::false_type> {};
template <
class F,
std::enable_if_t<is_noexcept_callable<F,int>::value,int> = 0
>
int evalInt(int x, TESTREF(F) f) noexcept
{
return static_cast<int>(f(x));
}
template <
class F,
std::enable_if_t<!is_noexcept_callable<F,int>::value,int> = 0
>
int evalInt(int x, TESTREF(F) f)
{
return static_cast<int>(f(x));
}
int id(int x) noexcept { return x; }
int thrower(int x) { throw(0); }
int main(int argc, char* argv[])
{
std::cout << std::boolalpha
<< noexcept(evalInt(1,id))
<< std::endl;
std::cout << std::boolalpha
<< is_noexcept_callable<decltype(thrower), int>::value
<< std::endl;
}
执行结果程序,但是根据编译器的不同,我得到了不同的结果:
$ g++ --std=c++14 test.cpp
$ ./a.out
true
false
$ clang++ --std=c++14 test.cpp
$ ./a.out
false
false
我不确定根据标准哪个是正确的。
更奇怪的是,如果我将上面代码中的第 5 行更改为#if 0
那么 gcc 会将代码编译为另一个不同的程序:
$ ./a.out
true
true
如您所见,第二个值已更改。 但是,它仅取决于宏未触及的thrower
函数的noexcept
规范。 对此有什么合理的解释,还是只是一个错误?
编辑
结果是在 Ubuntu 18.04(64 位)包存储库中使用 GCC 7.4.0 和 clang 6.0.0 获得的。
我只能在版本 8 之前的 GCC 中重现此错误。行为的差异是由于noexcept
说明符是 GCC 7 的 C++14 版本(但不是 Clang 的)中函数类型的一部分,尽管这是 C++17特征。 如果我们添加is_noexcept_callable
部分特化,就可以看到这is_noexcept_callable
:
template <class... Args>
struct is_noexcept_callable<int(&)(int), Args...>
: public std::false_type {};
template <class... Args>
struct is_noexcept_callable<int(int), Args...>
: public std::false_type {};
这突然产生了两个false
s :GCC 保留了函数类型的noexcept
属性,但在模板参数推导期间显式忽略它们,以便选择上述特化,尽管如果我们删除定义,错误消息会显示noexcept
:
prog.cc:30:5: note: template argument deduction/substitution failed:
prog.cc:28:22: error: incomplete type 'is_noexcept_callable<int (&)(int) noexcept, int>' used in nested name specifier
TESTREF
的定义会影响is_noexcept_callable
? 你问题的第二部分更微妙。 在这里,问题是is_noexcept_callable
在您在main
使用它之前已经用相关类型int(int) [noexcept]
实例化,但是它附加了 noexcept,因此结果is_noexcept_callable<int(int), int>::value
固定为 true。
decltype(id)
是int(int) [noexcept]
,其中[noexcept]
是我的符号,用于表达 GCC 附加到函数类型的瞬态异常规范。 因此evalInt(1,id)
导致实例化
is_noexcept_callable<F,int>
where F = int(&)(int) [noexcept]
当TESTREF = X&&
和F = int(int) [noexcept]
当TESTREF = X const&
因此,当您禁用 if 指令的第一个分支时,则is_noexcept_callable<int(int),int>::value == true
在noexcept(evalInt(1,id))
被处理后保持noexcept(evalInt(1,id))
,因为id
是 noexcept 并且这会传播在实例化链中。
因此,以下打印两个错误:
int main(int argc, char* argv[])
{
std::cout << std::boolalpha
<< noexcept(evalInt(1,thrower))
<< std::endl;
std::cout << std::boolalpha
<< is_noexcept_callable<decltype(thrower), int>::value
<< std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.