gpt4 book ai didi

C++ 创建通用 std::bind 的 std::packaged_task

转载 作者:行者123 更新时间:2023-11-30 01:46:30 25 4
gpt4 key购买 nike

我只是尝试为给定的 std::bind 创建一个 std::packaged_task

#include <functional>
#include <future>

class A
{
public:
template<class T>
void execute(T func)
{
std::packaged_task<T> task(func);
}
};

int main()
{
auto func = std::bind([](int x) { return x*x; }, 5);

A name;

name.execute(func);
}

main.cpp: In instantiation of 'void A::execute(T) [with T = std::_Bind(int)>]': main.cpp:20:20: required from here main.cpp:10:36: error: 'std::packaged_task(int)> > task' has incomplete type std::packaged_task task(func);

我正在使用 G++ 5.2.0 和 C++14。

有人有想法吗?

谢谢,

最佳答案

从 c++11 开始,无法将函数参数声明为 auto(我相信它是 c++17 的一部分)。不幸的是,我没有支持该功能的编译器,我不太确定它的语义,但解决方法是使用模板:

#include <future>
#include <functional>

template<class T>
void execute(std::function<T> func) // is a std::bind
{
std::packaged_task<T> task(func);
//...
}

你可以这样使用:

std::function<int()> func = std::bind([](int x) { return x*x; }, 5);
execute(func);

出现此错误的原因是 std::packaged_task 仅专用于 ReturnType(Args...) 形式的模板参数。因此,如果您传递不同的东西,例如从 std::bind 返回的 std::_Binderstd::function,它会显示为未定义。

编辑

关于您关于推导 std::function 类型的评论:

您可以使用 lambda 代替 std::bind()

如果你有一个 A 类,其函数 doSomething(int x) 就像你的评论中那样:

class A
{
public:
int doSomething(int x)
{
return x *x;
}
};

我们需要将执行函数更改为以下内容(参见 Yakk 的回答):

template<class F, class...Args>
void execute(F&& func, Args&&...args)
{
using zF = std::decay_t<F>&&;
using R = std::result_of_t< zF(Args...) >;
std::packaged_task<R()> task(
std::bind([func = std::forward<F>(func)](auto&&...args)mutable->R{
return std::move(func)(decltype(args)(args)...);
}, std::forward<Args>(args)...)
);
}

现在你可以像这样使用它了:

A a;

auto f = [](A& inst, int x) { return inst.doSomething(x); };
execute(f, a, 5);

// or

auto g = [&]() { return a.doSomething(5); };
execute(g);

注意

请注意 a 的生命周期,因为 packaged_task 可能会异步运行。

关于C++ 创建通用 std::bind 的 std::packaged_task,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33135304/

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