M.M*_*M.M 9 c++ function noexcept
这段代码编译并运行,抛出int:
#include <functional>
void r( std::function<void() noexcept> f ) { f(); }
void foo() { throw 1; }
int main()
{
r(foo);
}
Run Code Online (Sandbox Code Playgroud)
但是我希望编译器拒绝该行,r(foo);因为r只应传递一个noexcept函数.该noexcept说明符似乎被忽略.有没有办法实现这一目标?
编辑:这个问题是不同的是关于传递函数指针时应该转发的noexcept-ness的知识?因为我要求补救,特别是在这种情况下std::function.
我也偶然发现了这个问题。我的解决方案是使用委托对象(委托给std::function)。该委托有一个无例外的规范。它仍然可以改进(添加移动等)。
事情是这样的:
#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_;
};
Run Code Online (Sandbox Code Playgroud)
这通常用作异步接口中的契约,以指示所提供的处理程序不应抛出,例如:
struct Interface
{
virtual void doSomethingAsynchronous(
NoExceptDelegate<void(int)> onCompletionResult) = 0;
//...etc
};
Run Code Online (Sandbox Code Playgroud)
由于客户端是回调提供者,NoExceptDelegate因此提供者承诺所提供的不会失败。提供者应该确保至少std::function提供的是可调用的。