无法绑定可变函数并保存到 std::function

cannot bind variadic function and save to a std::function

我成功地实现了我自己的 thread_pool class,我可以提交可以 return 任何值但只能采用零参数的 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_nmy_func

的参数

为此,我成功地创建了一个可以接受可变数量参数的函数,但我没有设法将这个函数保存到我的 std::function 队列中。我读到这个 ​​link: 如何使用 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&&),不能接受左值。