Created
December 8, 2012 02:26
-
-
Save jbandela/4238255 to your computer and use it in GitHub Desktop.
Some C++ sugar for cocos2d-x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef JRB_COCOS_H | |
#include <stdexcept> | |
struct InitFailed:public std::exception{ | |
InitFailed():std::exception("init Failed"){} | |
}; | |
template<class T, class... Parms> | |
cocos2d::CCScene* createScene(Parms&&... p){ | |
CCScene * scene = NULL; | |
// 'scene' is an autorelease object | |
scene = CCScene::create(); | |
if(! scene)return nullptr; | |
// 'layer' is an autorelease object | |
T *layer = createWithInit<T>(std::forward<Parms>()...); | |
if(! layer)return nullptr; | |
// add layer as a child to scene | |
scene->addChild(layer); | |
// return the scene | |
return scene; | |
}; | |
template<class T,class... Parms> | |
T* createWithInit(Parms&&... p) | |
{ | |
T *pRet = nullptr; | |
try{ | |
pRet = new T(std::forward<Parms>(p)...); | |
if (pRet && pRet->init()) | |
{ | |
pRet->autorelease(); | |
return pRet; | |
} | |
else | |
{ | |
delete pRet; | |
return nullptr; | |
} | |
} | |
catch(const std::bad_alloc&){ | |
return nullptr; | |
} | |
catch(const InitFailed&){ | |
delete pRet; | |
return nullptr; | |
} | |
} | |
template<class T> | |
struct BaseWithCocosInit:public T{ | |
BaseWithCocosInit(){ | |
initSucceeded_ = T::init(); | |
if(!initSucceeded_){ | |
throw InitFailed(); | |
} | |
} | |
bool init(){return initSucceeded_;}// Do nothing | |
bool initSucceeded_; | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment