Search code examples
c++stdbind

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


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?


Solution

  • 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...); };
    }