C++11 - 如何修复无法检测带有 noexcept 说明符的函数声明的 noexcept 运算符

C++11 - How to fix noexcept operator that fails to detect function declaration with noexcept specifier

我正在为个人研究目的建立一个新的库,我正试图完全理解 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 编译标志时才会通过;我用 gcc8.1 和 clang5.0 做了 运行 测试。我没有用其他编译器测试过。

它因 c++11 或 c++14 标志而失败。谁能解释一下为什么?

谢谢

你的第一次测试,不成功:这次通过了

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 :

Until 17 : The noexcept-specification is not a part of the function type source : 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 现在属于类型