class ObjMgr { public: static ObjMgr & Instance(); template <typename T> void Register(const char* name) { m_creators[name] = &(ObjCreator<T>); } Abstract & GetObj(const string& objTypeCode); private: ObjMgr(void) {}; template <typename T> static shared_ptr<Abstract>& ObjCreator() { return move(std::shared_ptr<Abstract> (new T)); } typedef shared_ptr<Abstract>& (*PObjCreator)(); std::unordered_map<std::string, PObjCreator> m_creators; vector< shared_ptr<Abstract> > m_objs; //singleton static unique_ptr<ObjMgr> m_instance; static std::once_flag m_onceFlag; ObjMgr(const ObjMgr &) = default; ObjMgr& operator=(const ObjMgr &) = default; }; Abstract& ObjMgr::GetObj(const string& objTypeCode) { const shared_ptr<Abstract>& obj = m_creators[objTypeCode](); m_objs.push_back(move(obj)); return *(m_objs.back()); }
main()
objMgr.Register<Derived>("Derived");
Abstract
shared_ptr
move
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)