std :: function with C ++中的noexcept 17

时间:2016-12-22 23:16:12

标签: c++ function c++17 noexcept

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

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

int main()
{
    r1(foo);
}

最新版本的GCC和Clang在C ++ 17模式下拒绝来电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中的正确行为是什么?

1 个答案:

答案 0 :(得分:18)

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主干都会相应地诊断出来。