gpt4 book ai didi

c++ - 创建共享 packaged_task 接受带转发的参数

转载 作者:行者123 更新时间:2023-11-28 02:20:49 25 4
gpt4 key购买 nike

嗨,我不知道如何编写一个正确的队列绑定(bind)并执行传递给方法 OCRQueue::enqueue() 的 lambda 表达式

// the task queue
std::queue< std::function<void(OCRK*)> > tasks;

// add new work item to the pool
template<class F>
auto OCRQueue::enqueue(F&& f)
-> std::future<typename std::result_of<F(OCRK*)>::type>
{
using return_type = typename std::result_of<F(OCRK*)>::type;

auto task = std::make_shared< std::packaged_task<return_type()> >
(
// how to initialize this task so that it can be called
// task(OCRK*) passing the parameter to f(OCRK*)
std::bind
(
std::forward<F>(f)
)
);

std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);

// don't allow enqueueing after stopping the pool
if (stop)
throw std::runtime_error("enqueue on stopped thread_pool");

// this fails because task does not accept parameters
tasks.emplace([task](OCRK* ocr){ task(ocr); });
}
condition.notify_one();
return res;
}

目前这无法在“auto task =”上编译,因为 f 需要一个 OCRK* 类型的参数:

错误 6 error C2064: term does not evaluate to a function takeing 0 arguments C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xrefwrap 58 1 Skilja.PR.API

On: 1> d:\sourcecode\skilja\alpr\alpr\skilja.pr.api.native\OCRQueue.h(51) : 参见函数模板实例化'std::shared_ptr> std::make_shared, std::_Bind &,>>(std::_Bind &,> &&)' 正在编译

预期的用法是这样的:

OCRQueue ocrPool(std::thread::hardware_concurrency());
auto work = [](OCRK* ocr)
{
return ocr->DoSomething();
};
future<DoSomethingResult> result = ocrPool.enqueue(work);

OCRK* 将在出队并在另一个线程中执行时传递给入队函数。

最佳答案

要创建一个接受单个参数的可调用对象,您需要告诉 bind为参数使用占位符:

std::bind( std::forward<F>(f), std::placeholders::_1 )

这告诉bind留下未绑定(bind)的参数,调用函数对象时必须提供该参数。

但我不明白你为什么要使用 bind根本没有绑定(bind)任何东西,f已经是接受单个参数的可调用对象,为什么不将它传递给 packaged_task构造函数?

还有一个问题,就是你说你想要一个接受单个参数的任务,但是你已经声明了packaged_task<return_type()>。这是一项不带参数的任务。我想你想要:

auto task = std::make_shared< std::packaged_task<return_type(OCRK*)> >(std::forward<F>(f));

还有:

    tasks.emplace([task](OCRK* ocr){ task(ocr); });

这仍然会失败,因为 taskshared_ptr ,所以它是不可调用的。应该是:

    tasks.emplace([task](OCRK* ocr){ (*task)(ocr); });

关于c++ - 创建共享 packaged_task 接受带转发的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32591370/

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