[英]Passing member function to Template function
Given the following function:给定以下 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:将成员 function 作为参数传递给
ThreadPool::enqueue
的正确方法是什么,比如 object 是:
Foo foo
and the function is: function 是:
foo.do_something();
I have tried to use std::bind
and std::mem_fn
with or without "&" and all failed.我尝试使用带有或不带有“&”的
std::bind
和std::mem_fn
并且都失败了。
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:除了@IgorTandetnik 在评论中提到的内容之外,您还可以使用
std::bind
和std::mem_fn
将成员 function 传递给您的方法:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.