加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:29:11 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个用户可以在地图中存储不同类型数据的类.我为bool,int和std :: string创建了一个映射,并创建了模板函数,这样我就不必为每种类型重写get和set函数. 这是我的代码的最小版本: #include map#include string#include stdexcept#include iostre
我正在尝试创建一个用户可以在地图中存储不同类型数据的类.我为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

但为什么?

解决方法

两点:

>专业化应该在类之外(重要),否则不会编译
>专业化的正确语法如下:

//outside the class definition

template<>
std::map<std::string,bool>& Options::GetMap<bool>() {
                           //^^^^^^^^^ dont forget this!
      return bools_;
}
template<>
std::map<std::string,std::string>& Options::GetMap<std::string>() {
                                   //^^^^^^^^^ dont forget this!
      return strings_;
}
template<>
std::map<std::string,int>& Options::GetMap<int>() {
                           //^^^^^^^^^ dont forget this!
      return ints_;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读