在 std::function 上执行 "noexcept"?

Enforce "noexcept" on std::function?

此代码编译并运行,抛出 int:

#include <functional>

void r( std::function<void() noexcept> f ) { f(); }

void foo() { throw 1; }

int main()
{
    r(foo);
}

但是我希望编译器拒绝行 r(foo); 因为 r 应该只传递一个 noexcept 函数。 noexcept 说明符似乎被忽略了。有什么办法可以实现吗?

编辑:这个问题与 Is knowledge about noexcept-ness supposed to be forwarded when passing around a function pointer? 不同,因为我要求补救,特别是在 std::function 的情况下。

我也遇到过这个问题。我的解决方案是使用委托对象(委托给 std::function)。委托有一个 no-except 规范。它仍然可以改进(移动添加等)。

开始了:

#include <functional>

template <class FuncT>
struct NoExceptDelegate;

template <class R, class ... Args >
struct NoExceptDelegate<R(Args...)>
{
    NoExceptDelegate(std::function<R(Args...)>&& callback)
      : callback_(move(callback))
    {
        if (!callback_)
        {
            throw std::invalid_argument( "NoExceptDelegate requires a valid callback");
        }
    }

    template <class...ArgsU>
    R operator()(ArgsU&&... args) noexcept
    {
        return callback_(std::forward<ArgsU>(args)...);
    }

  private:
      std::function<R(Args...)> callback_;
};

这通常用作异步接口中的约定,以指示提供的处理程序不应抛出例如:

struct Interface
{
    virtual void doSomethingAsynchronous(
        NoExceptDelegate<void(int)> onCompletionResult) = 0;
    //...etc
};

由于客户端是回调提供者,NoExceptDelegate 是提供者承诺不会失败的承诺。提供者应确保至少 std::function provided 是可调用的。