How to use std::bind with std::function in C++11


std::bind in C++11 can be thought of as a general-purpose function adaptor. It takes a callable object and generates a new callable that “adapts” the parameter list of the original object.

So generally,

auto newCallable = bind(callable, arg_list)

So delving into an example, suppose we have a function template like this:

typedef std::function<void(void* one, void* two)> thread_pipe_func_t;

and a function which uses this function typedef to pass a function object in.

void *thread_pipe_spawn(void* lala, thread_pipe_func_t func);

and then you have a function that doesn’t quite “fit”, but you would like to be passed into thread_pipe_spawn.

void recorder_thread(void* one, void* two, int someInt) { 
// some stuff

You can do this:

namespace ph = std::placeholders;
thread_pipe_spawn(in, std::bind(recorder_thread, ph::_1, ph::_2, 5))

Jam that recorder_thread in for good!

Bear in mind that the extra variable being bound must be copy-able, as std::bind makes a copy of the bound variable. So if you want to bind a struct. Be sure to bind the pointer to the struct object, not the struct object itself.

ph::_1 and ph::_2 are placeholders. This means that the two variables passed into recorder_thread function, void* one and void* two are translated into the thread_pipe_func_t ‘s definition of void* one and void* two.

This can be used also to bind C++ member functions to functions which expect a C-style functions. (typically callbacks)

MainClass test = new MainClass();
CallbackHolder someclass = new CallbackHolder(); 
someclass.setCallback(std::bind(&MainClass::wanttocallthiscallback, test, ph::_1));

where definition of the class someclass is :

class CallbackHolder {
    // -- blah blah
    typedef std::function<void(int in)> callback_signature_t;
    void set(callback_signature_t cb) { m_callback = cb; }

Hope this is useful to you!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s