Search code examples
c++c++11stdstd-functionstdbind

To transform std::bind to std::function?


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()>?


Solution

  • 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