short方式std ::绑定成员函数到对象实例,无绑定参数 [英] Short way to std::bind member function to object instance, without binding parameters

查看:128
本文介绍了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...); };
}

这篇关于short方式std ::绑定成员函数到对象实例,无绑定参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆