gpt4 book ai didi

c++ - 在 std::function 上强制执行 "noexcept"?

转载 作者:可可西里 更新时间:2023-11-01 17:59:18 26 4
gpt4 key购买 nike

此代码编译并运行,抛出 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 的情况下。

最佳答案

我也遇到过这个问题。我的解决方案是使用委托(delegate)对象(委托(delegate)给 std::function)。委托(delegate)有一个 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_;
};

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

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

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

关于c++ - 在 std::function 上强制执行 "noexcept"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31602903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com