用法灵感来源于unity,打算改造cocos
class SGComponent { public: virtual void update(float delta){}; virtual void onStart(){} virtual void onDestroy(){}; virtual void onCreate(){}; }; class AudioComponent :public SGComponent { public: }; class RenderComponent :public SGComponent { public: }; class GameObject { public: template<class T> SGComponent* GetComponent() { return nullptr; }; template<> SGComponent* GetComponent<AudioComponent>() { return this->_audio; }; template<class T>void AddComponent(T * t){}; template<>void AddComponent(RenderComponent *t) { if (_render){} this->_render = t; }; template<>void AddComponent(AudioComponent *t) { if (_audio){} this->_audio = t; }; private: AudioComponent*_audio = nullptr; RenderComponent *_render = nullptr; }; int main(int argc,char *argv[]) { _CrtDumpMemoryLeaks(); GameObject obj; cout << obj.GetComponent<RenderComponent>(); system("pause"); return 0; }