I dislike having magic boxes scattered all over my code…how exactly do these two classes work to allow basically any function to be mapped to a function object even if the function<> has a completely different parameter set to the one im passing to boost::bind
It even works with different calling conventions (i.e. member methods are __thiscall under VC, but ‘normal’ functions are generally __cdecl or __stdcall for those that need to be compatible with C.
boost::functionallows anything with anoperator()with the right signature to be bound as the parameter, and the result of your bind can be called with a parameterint, so it can be bound tofunction<void(int)>.This is how it works (this description applies alike for
std::function):boost::bind(&klass::member, instance, 0, _1)returns an object like thiswhere the
return_typeandintare inferred from the signature ofklass::member, and the function pointer and bound parameter are in fact stored in the object, but that’s not importantNow,
boost::functiondoesn’t do any type checking: It will take any object and any signature you provide in its template parameter, and create an object that’s callable according to your signature and calls the object. If that’s impossible, it’s a compile error.boost::functionis actually an object like this:where the
return_typeandargument_typeare extracted fromSig, andfis dynamically allocated on the heap. That’s needed to allow completely unrelated objects with different sizes bind toboost::function.function_implis just an abstract classThe class that does all the work, is a concrete class derived from
boost::function. There is one for each type of object you assign toboost::functionThat means in your case, the assignment to boost function:
function_impl_concrete<void(int), unspecified_type>(that’s compile time, of course)When you call the function object, it calls the virtual function of its implementation object, which will direct the call to your original function.
DISCLAIMER: Note that the names in this explanation are deliberately made up. Any resemblance to real persons or characters … you know it. The purpose was to illustrate the principles.