Add utils::createInstance to instead macro CREATE_FUNC

This commit is contained in:
halx99 2020-08-25 13:49:45 +08:00
parent c8a665da40
commit d39f803459
4 changed files with 39 additions and 15 deletions

View File

@ -153,8 +153,8 @@ namespace utils
* @return Returns found node or nullptr with specified type 'T'
*/
template<typename T> inline
T findChild(Node* levelRoot, const std::string& name)
template<typename T>
inline T findChild(Node* levelRoot, const std::string& name)
{
return dynamic_cast<T>(findChild(levelRoot, name));
}
@ -164,12 +164,46 @@ namespace utils
* @return Returns found node or nullptr with specified type 'T'
*/
template<typename T> inline
T findChild(Node* levelRoot, int tag)
template<typename T>
inline T findChild(Node* levelRoot, int tag)
{
return dynamic_cast<T>(findChild(levelRoot, tag));
}
/**
* Create a Game Object instance, like CREATE_FUNC, but more powerful
* @return Returns a autorelease game object
* @limition: the init function finit must be public
*/
template<typename T, typename F, typename...Ts>
inline T* createInstance(F&& finit, Ts&&... args)
{
T* pRet = new(std::nothrow) T();
if (pRet && std::mem_fn(finit)(pRet, std::forward<_Types>(args)...)) {
pRet->autorelease();
return pRet;
}
else
{
delete pRet;
pRet = nullptr;
return nullptr;
}
}
/**
* Create a Game Object instance with 'bool T::init()' function, like CREATE_FUNC, but more powerful
* @return Returns a autorelease game object
* @limition: the init function finit must be public
*/
template<typename T>
inline T* createInstance()
{
return ::cocos2d::utils::createInstance<T>(&T::init);
}
/**
* Gets the md5 hash for the given file.
* @param filename The file to calculate md5 hash.

View File

@ -108,7 +108,7 @@ bool AppDelegate::applicationDidFinishLaunching() {
register_all_packages();
// create a scene. it's an autorelease object
auto scene = HelloWorld::createScene();
auto scene = utils::createInstance<HelloWorld>();
// run
director->runWithScene(scene);

View File

@ -26,11 +26,6 @@
USING_NS_CC;
Scene* HelloWorld::createScene()
{
return HelloWorld::create();
}
// Print useful error message instead of segfaulting when files are not there.
static void problemLoading(const char* filename)
{

View File

@ -30,15 +30,10 @@
class HelloWorld : public cocos2d::Scene
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__