c++ - 无法绑定(bind)可变函数并保存到 std::function

标签 c++ function c++11 variadic-templates stdbind

我成功地实现了我自己的 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_nmy_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/

相关文章:

function - TypeScript 中错误抛出函数的签名

javascript - 如何在 Rails UJS 响应中使用 javascript 函数

c++ - 没有返回类型的 main 的使用在 C++11 中被淘汰了吗?

c++ - 除非满足静态条件,否则阻止转换运算符编译

c++ - Shell_NotifyIcon 在系统托盘中创建空白、无响应的图标

c++ - 2 个值的容器(对于每个 float 一个可操作的整数)

c - 递归函数比较没有库函数的字符串

c++ - 我在这里使用 std::forward 还是 std::move?

c++ - OpenGL glutInit() : XOpenDisplay() causing segmentation fault

c++ - 具有前向声明类型的 Boost.TypeErasure