Last active
January 2, 2016 08:59
-
-
Save melpon/8280545 to your computer and use it in GitHub Desktop.
cocos2d-x の CREATE_FUNC を C++ っぽくしてみた
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 CREATE_FUNC_HPP_INCLUDED | |
#define CREATE_FUNC_HPP_INCLUDED | |
/* | |
使い方: | |
class TestLayer : public cocos2d::Layer { | |
public: | |
bool init(); | |
CREATE_FUNC(TestLayer); | |
}; | |
と書く代わりに、以下のように書く。 | |
class TestLayer : public cocos2d::Layer, create_func<TestLayer> { | |
public: | |
bool init(); | |
using create_func::create; | |
}; | |
CREATE_FUNC マクロと違い、引数はいくつでも大丈夫。 | |
class TestLayer : public cocos2d::Layer, create_func<TestLayer> { | |
public: | |
bool init(int a, std::string b); | |
using create_func::create; | |
}; | |
auto test = TestLayer::create(10, "abc"); | |
*/ | |
template<class Derived> | |
struct create_func { | |
template<class... Args> | |
static Derived* create(Args&&... args) { | |
auto p = new Derived(); | |
if (p->init(std::forward<Args>(args)...)) { | |
p->autorelease(); | |
return p; | |
} else { | |
delete p; | |
return nullptr; | |
} | |
} | |
}; | |
#endif // CREATE_FUNC_HPP_INCLUDED |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment