简体   繁体   中英

Passing member function to Template function

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM