如何将参数传递给std :: bind到函数? [英] How to pass argument to std::bind to a function?

查看:268
本文介绍了如何将参数传递给std :: bind到函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下使用std :: bind的代码:

I have the following code which used std::bind :

 EventListenerCustom* _createNewObjectlistener = 
eventDispatcher->addCustomEventListener(Constants::MY_EVENT, 
std::bind(&MyClass::MyFunction, this, std::placeholders::_1));

似乎我创建了许多不同类型的对象侦听器,其中唯一的区别是事件,而函数被调用。如果我想将上述代码封装到一个函数中:

It seems I create many different kinds of object listeners, where the only difference is the event, and the function being called. If I wanted to encapsulate the above code into a function:


  • 如何将MyClass :: MyFunction作为函数的参数传递? / li>
  • 函数签名和参数是什么样的?

我想函数看起来像这样:

I imagine the function would look something like this:

EventListenerCustom* MyFunc(<What Goes Here> functionToBeBound,<What goes here> object,std::string EVENT){
    EventListenerCustom* eventListener = eventDispatcher->addCustomEventListener(EVENT, std::bind(functionToBeBound, object, std::placeholders::_1));
    return eventListener;
}

函数应该是什么样?我怎么称呼它?

What should the function look like ? And How do I call it? What would the calling code look like?

编辑:具体细节:

我有很多侦听器对象,它们是以相同的方式创建:

I have many listener objects which are created in identical ways:

auto eventDispatcher = _dragNode->getEventDispatcher();

_createNewObjectlistener = eventDispatcher->addCustomEventListener(Constants::MY_EVENT, std::bind(&MyClass::myOtherFunction, this, std::placeholders::_1));

_moveNewObjectlistener = eventDispatcher->addCustomEventListener(Constants::MY_EVENT2 std::bind(&MyClass::myFunction, this, std::placeholders::_1));

Constants :: MY_EVENT等只是const char *。

Constants::MY_EVENT etc are just const char* .

唯一的区别是调用了Function,并将字符串常量用作事件名称。如何将其封装到函数中?我在下面尝试了John Zwinck的解决方案,但是由于某种原因,由于编译器抱怨,我无法将其编译:

The only difference is the Function being called, and the string constant used as an event name. How can I encapsulate this into a function ? I have tried John Zwinck's solution below, but for some reason I can't get it to compile because the compiler complains:

: No viable conversion from '__bind<void (*&)(cocos2d::EventCustom *), MyNameSpace::MyClass *, const std::__1::placeholders::__ph<1> &>' to 'const std::function<void (EventCustom *)>'


推荐答案

为简化起见,请为指向 MyClass 中具有适当签名的任何成员函数的指针创建一个typedef:

To make it simpler, create a typedef for a pointer to any member function in MyClass which has the appropriate signature:

typedef void (MyClass::*MyMemberFn)(int); // replace int and void as needed

然后:

EventListenerCustom* MyFunc(MyMemberFn functionToBeBound, MyClass* object, std::string EVENT){
    return eventDispatcher->addCustomEventListener(EVENT, std::bind(functionToBeBound, object, std::placeholders::_1));
}

这篇关于如何将参数传递给std :: bind到函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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