在C++ 17 noexcept has been added to the type system中:

void r1( void (*f)() noexcept ) { f(); }
void foo() { throw 1; }

int main()
{
    r1(foo);
}

在C++ 17模式下,最新版本的GCC和Clang拒绝调用r1(foo),因为void (*)()无法隐式转换为void (*)() noexcept

但是用std::function代替:
#include <functional>

void r2( std::function<void() noexcept> f ) { f(); }
void foo() { throw 1; }

int main()
{
    r2(foo);
}

Clang接受该程序,但显然忽略了noexcept说明符;和g++给出了一个关于std::function<void() noexcept>的奇怪错误。

C++ 17中第二个程序的正确行为是什么?

最佳答案

std::function的定义在当前工作草案中未更改:

template<class T>
class function; // not defined

template<class R, class... ArgTypes>
class function<R(ArgTypes...)> {
    /* ... */
};

由于void() noexcept与部分专业名称不匹配,因此std::function<void() noexcept>是不完整的类型。 Clang和GCC主干均会对此进行诊断。

10-08 13:31
查看更多