【发布时间】:2019-04-20 02:56:13
【问题描述】:
我有以下使用 std::bind 的代码:
EventListenerCustom* _createNewObjectlistener =
eventDispatcher->addCustomEventListener(Constants::MY_EVENT,
std::bind(&MyClass::MyFunction, this, std::placeholders::_1));
似乎我创建了许多不同类型的对象侦听器,唯一的区别是事件和被调用的函数。如果我想把上面的代码封装成一个函数:
- 如何将 MyClass::MyFunction 作为参数传递给函数?
- 函数签名和参数是什么样的?
我想这个函数看起来像这样:
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;
}
函数应该是什么样的?我怎么称呼它?调用代码是什么样的?
编辑:具体细节:
我有许多以相同方式创建的侦听器对象:
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* 。
唯一的区别是被调用的函数,以及用作事件名称的字符串常量。我怎样才能把它封装成一个函数?我在下面尝试了 John Zwinck 的解决方案,但由于某种原因我无法编译它,因为编译器会抱怨:
: No viable conversion from '__bind<void (*&)(cocos2d::EventCustom *), MyNameSpace::MyClass *, const std::__1::placeholders::__ph<1> &>' to 'const std::function<void (EventCustom *)>'
【问题讨论】: