gpt4 book ai didi

c++ - 如何将函数指针传递给绑定(bind)?

转载 作者:行者123 更新时间:2023-11-28 04:19:36 25 4
gpt4 key购买 nike

我有以下代码:

_createNewObjectlistener = eventDispatcher->addCustomEventListener(Constants::EVENT_CREATE_OBJECT, std::bind(&ObjectPlacementManager::receiveCreateObjectEvent, this, std::placeholders::_1));
_eventListeners.insert(_createNewObjectlistener);

_moveNewObjectlistener = eventDispatcher->addCustomEventListener(Constants::EVENT_MOVE_NEW_OBJECT, std::bind(&ObjectPlacementManager::receiveMoveCurrentGameObjectEvent, this, std::placeholders::_1));
_eventListeners.insert(_moveNewObjectlistener);

.... many more listeners created

由于每个监听器的创建代码之间的唯一区别是 Constant::EVENT_NAME和被调用的函数,我试图将它封装到一个函数中。

bind 的结果必须是 const std::function<void(EventCustom*)>& 类型

类似ObjectPlacementManager::receiveMoveCurrentGameObjectEvent的函数都有相同的签名:

void receiveMoveCurrentGameObjectEvent(EventCustom* event){
....
}

我试过:How to pass argument to std::bind to a function?

typedef void (*callback_function)(EventCustom*);

EventListenerCustom* createCustomListener(callback_function func, std::string EVENT){
auto eventDispatcher = _dragNode->getEventDispatcher();
auto listener = eventDispatcher->addCustomEventListener(EVENT, std::bind(&func, this, std::placeholders::_1));
_eventListeners.insert(_createNewObjectlistener);
return listener;
}

但我得到的错误是:

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

我也试过做一个函数:

EventListenerCustom* createCustomListener(void* func, std::string EVENT){
auto eventDispatcher = _dragNode->getEventDispatcher();
auto listener = eventDispatcher->addCustomEventListener(EVENT, std::bind(func, this, std::placeholders::_1));
return listener;
}

但我得到的错误是:

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

最佳答案

第一个错误是因为您获取了函数指针的地址。因此,您将一个指向函数指针的指针传递给 std::bind

第二个错误是因为您使用了 void * 并以某种方式期望它起作用!

试试这个 MCVE:

struct Event {};

struct Dispatcher {
void addListener(int, const std::function<void(Event *)> &) {}
};

struct Manager {
void receive(Event *) {}

void addListener(int type, void (Manager::*receiver)(Event *)) {
dis.addListener(type, std::bind(receiver, this, std::placeholders::_1));
}

void test() {
addListener(42, &Manager::receive);
}

Dispatcher dis;
};

关于c++ - 如何将函数指针传递给绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55770302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com