切换模板类型

Max*_*rai 3 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
        {
            // [?]
        }
};
Run Code Online (Sandbox Code Playgroud)

所以,我有一些关联容器存储确切的数据类型.现在我想在设置中添加一些值:settings.Push<int>("WorldSize", 1000);并得到它:settings.Get<int>("WorldSize");.但是由于传递类型到模板中如何切换需要地图?

或者,也许,你知道更好的方式,谢谢.

Set*_*gie 8

如果编译器支持此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
Run Code Online (Sandbox Code Playgroud)

请注意,方法不是const因为map<>::operator[]不是const.

此外,如果某人尝试使用的模板类型不是您提供的专业化类型,则会出现链接器错误,因此您的代码不会出现异常或其他任何错误.哪个是最佳的.


1如果没有,请参阅@ gwiazdorrr的答案

  • 虽然模板函数的特化很简洁,但它们并不是特定于C++ 11的.由于它们与正常函数重载的交互方式,它们在所有情况下都不合适.这是适当的情况之一.见http://www.gotw.ca/gotw/049.htm (2认同)

gwi*_*rrr 8

首先,因为在C++ 11之前你不能专门化函数,你的成员函数必须在签名上有所不同 - 返回类型不计算.根据我在某些编译器上的经验,你可以不用它,但像往常一样 - 你应该保持你的代码尽可能接近标准.

也就是说你可以添加一个不会影响性能和调用函数方式的伪参数:

public:
    template <typename T>
    T Get(const std::string &key) const
    {
        return GetInner(key, (T*)0);
    }

private:
    int GetInner(const std::string& key, int*) const
    {
        // return something from mIntegerStorage
    }

    float GetInner(const std::string& key, float*) const
    {
        // return something from mFloatStorage
    }
Run Code Online (Sandbox Code Playgroud)

等等.你明白了.

  • 您不需要将虚拟指针添加到接口,它只需转发到'GetInner(key,(T*)0)',即额外指针是一个不应修改公共接口的细节. (4认同)