将成员函数传递给模板函数

Passing member function to Template function

本文关键字:函数 成员      更新时间:2023-10-16

给定以下函数:

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::bindstd::mem_fn,但都失败了。

除了@IgorTandetnik在注释中提到的内容外,您还可以将std::bindstd::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;
}