我成功地实现了我自己的 thread_pool
类,我可以在其中提交可以返回任何值但只能采用零参数的 lambda。我想改进它,使其可以像 std::async
一样工作,其中可以按如下方式调用它:std::async(my_function, arg_1, arg_2, ... , arg_n)
。正如我现在拥有的那样,它看起来如下:
template<typename T>
auto enqueue_task(T&& task) -> std::future<decltype(task())>
{
auto wrapper = std::make_shared<std::packaged_task<decltype(task())()>>(std::forward<T>(task));
{
//some mutex
std::unique_lock<std::mutex> mutex(mutex_);
//The task is added to a queue of std::function<void()>
tasks_.emplace([=] {(*wrapper)(); });
}
has_work_.notify_one();
return wrapper->get_future();
}
我理想的解决方案是这样的,我可以像这样将参数传递给 thread_pool
中的函数:
pool.enqueue_task(my_function, arg_1, arg_2, ..., arg_n)
其中 arg_1, ..., arg_n
是 my_func
的参数
为此,我成功地创建了一个可以接受可变数量参数的函数,但我没有设法将这个函数保存到我的 std::function 队列中。我在这个链接上读到: Passing a variadic function as argument如何使用 std::bind 实现我的目标。然而,我还没有设法实现我的目标。以下是我的理解,结果是行不通的:
//some function with variadic arguments
template <typename... Args>
void test1(Args&&... args)
{
}
void test2(int a)
{
}
//main method
std::function<void()> a = std::bind(test2, 2) //works
std::function<void()> b = std::bind(test1<int>, 1) //does not work
最佳答案
std::bind
将参数作为左值传递。来自 cppreference :
the ordinary stored argument arg is passed to the invokable object as lvalue argument
当您指定 test1<int>
时, 函数变为 void test1(int&&)
, 不能接受左值。
关于c++ - 无法绑定(bind)可变函数并保存到 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50456389/