Skip to content

Instantly share code, notes, and snippets.

@jbandela
Created December 8, 2012 02:26
Show Gist options
  • Save jbandela/4238255 to your computer and use it in GitHub Desktop.
Save jbandela/4238255 to your computer and use it in GitHub Desktop.
Some C++ sugar for cocos2d-x
#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