1

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.

4
  • 1
    Try pool.enqueue([foo]() { foo.do_something(); }); Commented Jun 7, 2020 at 1:47
  • Did you try: pool.enqueue([foo]{foo.do_something();}) ? Commented Jun 7, 2020 at 1:53
  • Instead of saying you "tried bind and mem_fun", show us the code you tried. Commented Jun 7, 2020 at 5:21
  • For a non-overloaded non-template function you can also use pool.enqueue(&Foo::do_something, &foo, other_args_to_do_something...). Commented Jun 7, 2020 at 11:50

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

What is the correct syntax if do_something take parameters, say two ints?
@BulGali I updated the answer for a function with some parameters.
For some reason I get: /functional:467:70: error: no matching function for call to 'std::tuple<AlgoTravel*, std::__cxx11::basic_string...>. Any idea why that might happen? Is there a special syntax if the parameters are passed by reference? say "std::string &str"?
@BulGali If you are going to pass one parameter (e.g. str) by reference, then pass the parameter with std::ref(str). For const-reference parameters, you can use std::cref() instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.