short方式std ::绑定成员函数到对象实例,无绑定参数

short方式std ::绑定成员函数到对象实例,无绑定参数

问题描述:

我有一个成员函数有几个参数。我想绑定到一个特定的对象实例,并将此传递给另一个函数。我可以使用占位符:

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?

我认为这将工作:

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

那么:

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

注意:您需要重载才能处理CV限定的成员函数。即:

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