Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short way to std::bind member function to object instance, without binding parameters

Tags:

c++

stdbind

I have a member function with several arguments. I'd like to bind it to a specific object instance and pass this to another function. I can do it with placeholders:

// actualInstance is a MyClass*
auto callback = bind(&MyClass::myFunction, actualInstance, _1, _2, _3);

But this is a bit clumsy - for one, when the number of parameters changes, I have to change all the bind calls as well. But in addition, it's quite tedious to type all the placeholders, when all I really want is to conveniently create a "function pointer" including an object reference.

So what I'd like to be able to do is something like:

auto callback = objectBind(&MyClass::myFunction, actualInstance);

Does anyone know some nice way to do this?

like image 634
lethal-guitar Avatar asked Feb 10 '13 22:02

lethal-guitar


1 Answers

I think this will work:

template<typename R, typename C, typename... Args>
std::function<R(Args...)> objectBind(R (C::* func)(Args...), C& instance) {
    return [=](Args... args){ return (instance.*func)(args...); };
}

then:

auto callback = objectBind(&MyClass::myFunction, actualInstance);

note: you'll need overloads to handle CV-qualified member functions. ie:

template<typename R, typename C, typename... Args>
std::function<R(Args...)> objectBind(R (C::* func)(Args...) const, C const& instance) {
    return [=](Args... args){ return (instance.*func)(args...); };
}
like image 68
Pubby Avatar answered Oct 07 '22 00:10

Pubby