C ++ 11-如何修复使用noexcept指定符无法检测到函数声明的noexcept运算符

时间:2019-05-04 11:45:31

标签: c++11 decltype noexcept

我正在为个人研究目的而建立一个新的库,并且我试图完全了解c ++标准库工具和核心功能。现在我在理解noexcept运算符时遇到问题。

我写了一些涉及noexcept运算符的测试示例,但我对以下声明的结果感到困惑:

...
void no_throw() noexcept;

static_assert(noexcept(no_throw), "This should be true");
static_assert(noexcept((std::declval<decltype(no_throw)>())()), "this also should be true");
...

我希望此代码可以编译,但是仅在使用c ++ 17 compile标志时第二个断言才通过;我确实使用gcc8.1和clang5.0进行了测试。我尚未使用其他编译器进行测试。

使用c ++ 11或c ++ 14标志失败。有人可以解释一下为什么吗?

谢谢

1 个答案:

答案 0 :(得分:1)

您的第一个测试不起作用:此通行证

void no_throw() noexcept(true) {};
void do_throw() noexcept(false) {};

static_assert(noexcept(no_throw), "");
static_assert(noexcept(do_throw), "");

应该是:

void no_throw() noexcept(true) {};
void do_throw() noexcept(false) {};

static_assert(noexcept(no_throw()), "");
static_assert(!noexcept(do_throw()), "");

然后为什么只在17中:

  

直到17:noexcept规范不是该功能的一部分   类型   来源:https://en.cppreference.com/w/cpp/language/noexcept_spec

因此,如果您在11中运行此代码:

template<class T>
   struct TD;

TD<decltype(no_throw)> e;
TD<decltype(std::declval<decltype(no_throw)>())> e2;

您得到了:

prog.cc:14:24: error: aggregate 'TD<void()> e' has incomplete type and cannot be defined
 TD<decltype(no_throw)> e;
                        ^
prog.cc:15:50: error: aggregate 'TD<void (&)()> e2' has incomplete type and cannot be defined
 TD<decltype(std::declval<decltype(no_throw)>())> e2;

在17中:

prog.cc:14:24: error: aggregate 'TD<void() noexcept> e' has incomplete type and cannot be defined
 TD<decltype(no_throw)> e;
                        ^
prog.cc:15:50: error: aggregate 'TD<void (&)() noexcept> e2' has incomplete type and cannot be defined
 TD<decltype(std::declval<decltype(no_throw)>())> e2;

请参见,在17中,noexcept现在是类型