Short way to std::bind member function to object i

2019-02-12 05:23发布

问题:

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?

回答1:

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


标签: c++ stdbind