簡體   English   中英

為什么 std::string 不是模板常量參數的有效類型?

[英]Why is std::string not a valid type for a template constant parameter?

我正在嘗試創建一個 class ,用戶可以在其中在地圖中存儲不同類型的數據。 我為 bool、int 和 std::string 創建了 map 並創建了模板函數,這樣我就不必為每種類型重寫 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

但為什么?

如果我理解正確,您正在嘗試專門化 function 模板GetMap() 但是您的語法不正確; 你可能想要:

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

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

等等。

兩點:

  • 特化應該在class之外(重要),否則編譯不出來
  • 專業化的正確語法如下:

     //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_; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM