首页 > 解决方案 > 将成员函数传递给模板函数

问题描述

给定以下功能:

template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) 
    -> std::future<typename std::result_of<F(Args...)>::type>
{
    using return_type = typename std::result_of<F(Args...)>::type;

    auto task = std::make_shared< std::packaged_task<return_type()> >(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );

    std::future<return_type> res = task->get_future();
    return res;
}

将成员函数作为参数传递的正确方法是什么ThreadPool::enqueue,比如对象是:

Foo foo

功能是:

foo.do_something();

我尝试使用std::bindandstd::mem_fn有或没有“&”,但都失败了。

标签: c++c++11

解决方案


除了@IgorTandetnik 在评论中提到的内容之外,您还可以使用std::bindwithstd::mem_fn将成员函数传递给您的方法:

struct Foo
{
   void do_something() {}
   void do_something_else(int x, int y, std::string str) {}
};

int main()
{
   Foo foo;
   ThreadPool pool;

   auto func_sth = std::bind(std::mem_fn(&Foo::do_something), foo);
   auto func_sth_else = std::bind(std::mem_fn(&Foo::do_something_else), foo, 10 , 11, "hi");

   pool.enqueue(func_sth);
   pool.enqueue(func_sth_else);

   return 0;
}

推荐阅读