c++ - 为什么 std::string 不是模板常量参数的有效类型?

标签 c++ templates

我正在尝试创建一个类,用户可以在其中将不同类型的数据存储在 map 中。我已经为 bool、int 和 std::string 创建了一个映射并创建了模板函数,这样我就不必为每种类型重写 get 和 set 函数。

这是我的代码的最小版本:

#include <map>
#include <string>
#include <stdexcept>
#include <iostream>

class Options {
public:
    template<class T>
    void Set(const std::string& name, const T& value) {
        GetMap<T>()[name] = value;
    }
    template<class T>
    T Get(const std::string& name) {
        auto it = GetMap<T>().find(name);
        if(it == GetMap<T>().end()) {
            throw std::runtime_error(name + " not found");
        }
        return it->second;
    }
private:
    std::map<std::string, int> ints_;
    std::map<std::string, std::string> strings_;
    std::map<std::string, bool> bools_;

    template<class T>
    std::map<std::string, T>& GetMap();
    template<bool>
    std::map<std::string, bool>& GetMap() {
        return bools_;
    }
    template<std::string> // error
    std::map<std::string, std::string>& GetMap() {
        return strings_;
    }
    template<int>
    std::map<std::string, int>& GetMap() {
        return ints_;
    }
};

int main() {
    Options o;
    o.Set("test", 1234);
    o.Set<std::string>("test2", "Hello World!");
    std::cout << o.Get<int>("test") << std::endl
              << o.Get<std::string>("test2") << std::endl;
}

我收到以下错误:

error: 'struct std::basic_string<char>' is not a valid type for a template constant parameter

但为什么呢?

最佳答案

如果我没理解错的话,您正在尝试特化函数模板 GetMap()。但是你的语法不正确;你可能想要:

template<class T>
std::map<std::string, T>& GetMap();

template<>
std::map<std::string, bool>& GetMap<bool>() {
    return bools_;
}

等等。

关于c++ - 为什么 std::string 不是模板常量参数的有效类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5801601/

相关文章:

c++ - Libtool 版本不匹配

c++ - 尝试使用文件描述符从文件中读取会打印数字和斜线到控制台

c++ - 使用 QPrintPreviewDialog 时内容不显示预览

C++ - 如何获取结构的最后一个成员类型以及从现有对象访问它的方法?

C++,模板化指向函数的指针

c++ - OpenCV 功能检测和匹配 - 绘图匹配段错误

c++ - 当第一个字符串在预处理器指令中定义而第二个字符串在 C++ 中为常量时,如何连接 2 个字符串?

c++ - 什么是 boost 密集 C++/模板编译的良好 CPU/PC 设置?

javascript - 使用 Gulpjs 编译客户端 Jade 模板

c++ - 如何使用策略在类中添加额外的功能层?