c++ - 切换模板类型

标签 c++ templates types map

我想为我的游戏做一些存储。现在代码如下所示:

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"); .但是,由于将类型传递到模板,如何切换需要映射?

或者,也许,您知道更好的方法,谢谢。

最佳答案

如果你的编译器支持这个1,你可以使用模板函数特化:

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); // 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

关于c++ - 切换模板类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8220045/

相关文章:

pointers - 带指针的 Golang 类型断言

C# 类型比较 : Type. 等于 vs 运算符 ==

vb.net - 您可以将 "type"作为参数传递吗?

c++ - Ubuntu 不提供包含 uint24_t 类型的 Clang 的 stdint

c++ - 从主目录执行时,在 Ubuntu 16.04 的 usr/local/bin 中安装的 C++ 应用程序无法正确运行

c++ - 使用 opengl c++ 的天空盒问题

javascript - 为什么我的 Django 表单显示选择不可用错误?

c++ - C++ 中的数组初始化(非字符串)

c++ - 接受任何 STL 容器的函数

html - 如何将HTML图片/文字放在div中的同一行?