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

梦想与她 提交于 2019-12-18 19:16:11

问题


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


来源:https://stackoverflow.com/questions/14803112/short-way-to-stdbind-member-function-to-object-instance-without-binding-param

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!