Reputation: 157
Given the following function:
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;
}
What's the right way to pass a member function to ThreadPool::enqueue
as parameter, say the object is:
Foo foo
and the function is:
foo.do_something();
I have tried to use std::bind
and std::mem_fn
with or without "&" and all failed.
Upvotes: 1
Views: 389
Reputation: 8427
In addition to what @IgorTandetnik has mentioned in the comments, you can also use std::bind
with std::mem_fn
to pass a member function to your method:
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;
}
Upvotes: 1