lua 这种脚本语言用久了,总觉得反射机制就应该理所当然的嵌入在语言特性里。
比如希望根据自己传的类名变量,动态去 new 一些实例。在 lua ,js 里做起来就非常简单,然而在 c++里面做起来,就需要稍微费些周折。
好在 c++ 宏定义 支持传入参数, 仿佛就是专门给反射机制设计的。
写的时候参考 cocos2dx CREATE_FUNC 这个宏
#define CREATE_FUNC(__TYPE__) \
static __TYPE__* create() \
{ \
__TYPE__ *pRet = new(std::nothrow) __TYPE__(); \
if (pRet && pRet->init()) \
{ \
pRet->autorelease(); \
return pRet; \
} \
else \
{ \
delete pRet; \
pRet = NULL; \
return NULL; \
} \
}
如果手写,需要写很多类似这样长长的大同小异的代码:
EventListenerCustom* listener = nullptr;
listener = EventListenerCustom::create(GG_EVENT_TEST1, [=](EventCustom* event){
TestCommand command;
(&command)->execute(event);
});
_dispatcher->addEventListenerWithFixedPriority(listener, 1);
listener = EventListenerCustom::create(GG_EVENT_ENTER_GAME, [=](EventCustom* event){
EnterGameCommand command;
(&command)->execute(event);
});
_dispatcher->addEventListenerWithFixedPriority(listener, 1);
#define MAP_EVENT_COMMAND(__EVENTNAME__,__COMMANDNAME__,__DISPATCHER__) \
{\
EventListenerCustom* listener = nullptr; \
listener = EventListenerCustom::create(__EVENTNAME__, [=](EventCustom* event){ \
__COMMANDNAME__ command; \
(&command)->execute(event); \
}); \
__DISPATCHER__->addEventListenerWithFixedPriority(listener, 1); \
}
MAP_EVENT_COMMAND(GG_EVENT_TEST1, TestCommand, _dispatcher)
MAP_EVENT_COMMAND(GG_EVENT_ENTER_GAME, EnterGameCommand, _dispatcher)