1

See the code below

queue<function<void()> > tasks;

void add_job(function<void(void*)> func, void* arg) {
    function<void()> f = bind(func, arg)();
    tasks.push( f );
}

func is the function I want to add to the tasks which has argument is arg.

How can I do to use std::bind to bind its argument so that it can be assigned to the object of std::function<void()>?

JeJo
  • 30,635
  • 6
  • 49
  • 88
Torch
  • 13
  • 4

2 Answers2

3

How can I do to use std::bind to bind its argument so that it can be assigned to the object of function<void()>?

The std::bind returns an unspecified callable object, which can be stored in the std::function directly. Therefore you required only

function<void()> f = bind(func, arg); // no need to invoke the callable object
tasks.push( f );

However, I would recommend using lambdas (since C++11) instead of std::bind.

Secondly, having global variables are also not a good practice. I would propose the following example code. Let the compiler deduce the type of the passed functions and their (variadic) arguments (function-template).

template<typename Callable, typename... Args>
void add_job(Callable&& func, Args const&... args)
{
    // statically local to the function
    static std::queue<std::function<void()>> tasks;
    // bind the arguments to the func and push to queue
    tasks.push([=] { return func(args...); });
}

void fun1(){}
void fun2(int){}

int main()
{
    add_job(&fun1);
    add_job(&fun2, 1);
    add_job([]{}); // passing lambdas are also possible
}

See a demo in

JeJo
  • 30,635
  • 6
  • 49
  • 88
  • It's so kind of u to offer these useful skills, I can't appreciate you more, thanks! – Torch Nov 04 '22 at 07:32
  • 3
    @Torch You should upvote the answers that you fin useful. Also, once the time requires passes please accept the answer that solved your issue if any. – bolov Nov 04 '22 at 07:50
  • How would you pop and work on tasks pushed to a local scoped `static` queue? – Jakob Stark Nov 04 '22 at 08:11
  • 1
    @JakobStark That is when we required struct/ classes which encapsulate the queue. Here in the example it could be also via function return, `std::queue> const& add_job(...`.... – LernerCpp Nov 04 '22 at 08:20
0

Just bind it, don't execute it.

function<void()> f = bind(func, arg);
tasks.push( f );
GAVD
  • 1,977
  • 3
  • 22
  • 40