c – 切换模板类型
发布时间:2020-12-16 10:43:19 所属栏目:百科 来源:网络整理
导读:我想为我的游戏制作一些存储空间.现在代码看起来像: class WorldSettings{ private: std::mapstd::string,int mIntegerStorage; std::mapstd::string,float mFloatStorage; std::mapstd::string,std::string mStringStorage; public: template typename T T
我想为我的游戏制作一些存储空间.现在代码看起来像:
class WorldSettings { private: std::map<std::string,int> mIntegerStorage; std::map<std::string,float> mFloatStorage; std::map<std::string,std::string> mStringStorage; public: template <typename T> T Get(const std::string &key) const { // [?] } }; 所以,我有一些关联容器存储确切的数据类型.现在我想在设置中添加一些值:settings.Push< int>(“WorldSize”,1000);并得到它:settings.Get< int>(“WorldSize”);.但是由于传递类型到模板中如何切换需要地图? 或者,也许,你知道更好的方式,谢谢. 解决方法
如果编译器支持this1,则可以使用模板函数特化:
class WorldSettings { private: std::map<std::string,std::string> mStringStorage; public: template <typename T> T Get(const std::string &key); // purposely left undefined }; ... template<> int WorldSettings::Get<int>(const std::string& key) { return mIntegerStorage[key]; } template<> float WorldSettings::Get<float>(const std::string& key) { return mFloatStorage[key]; } // etc 请注意,方法不是const,因为map<> :: operator []不是const. 此外,如果某人尝试使用的模板类型不是您提供的专业化类型,则会出现链接器错误,因此您的代码不会出现异常或其他任何错误.哪个是最佳的. 1如果不是,请参阅@gwiazdorrr’s answer (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |