Skip to content

Instantly share code, notes, and snippets.

@melpon
Last active January 2, 2016 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melpon/8280545 to your computer and use it in GitHub Desktop.
Save melpon/8280545 to your computer and use it in GitHub Desktop.
cocos2d-x の CREATE_FUNC を C++ っぽくしてみた
#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