我想为我的游戏做一些存储空间。现在代码看起来像这样:
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");。但是如何将需要的map类型传递到模板中?
或者,也许你知道更好的方法,谢谢。
发布于 2011-11-22 07:46:32
Seth的答案是理想的,但是如果您不能访问C++11编译器,那么您可以使用模板类专门化来代替它。它要冗长得多,但保持相同的功能。
class WorldSettings
{
template<class T>
struct Selector;
template<class T>
friend struct Selector;
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)
{
return Selector<T>::Get(*this)[key];
}
};
template<>
struct WorldSettings::Selector<int>
{
static std::map<std::string, int> & Get(WorldSettings &settings)
{
return settings.mIntegerStorage;
}
};
template<>
struct WorldSettings::Selector<float>
{
static std::map<std::string, float> & Get(WorldSettings &settings)
{
return settings.mFloatStorage;
}
};
// etc.发布于 2011-11-22 08:59:56
在C++03中,我建议在容器的类型中使用‘boost::any’,并使用。你需要一个单一的访问器:
std::map<std::string,boost::any> storage;
template <typename T> getValue( std::string const & key ) {
return boost::any_cast<T>( storage[key] );
}这是一个粗略的草图,作为一个成员函数,它应该是const,它应该使用‘map::find’在搜索时不修改容器,它应该处理无效的joeys,并可能将boost异常重新映射到您自己的应用程序异常中。
https://stackoverflow.com/questions/8220045
复制相似问题