C++ unordered_map 使用模板

c++ unordered map using templates

我正在尝试使用 C++ 中的模板声明无序映射。但是,由于我希望该对象是原始数据类型之一,所以我不想仅为一个对象声明自定义 class。

我试过使用:

template <class T> std::unordered_map<int, T> storedObj;

但我不断收到错误消息:‘storedObj’未在此范围内声明

下面是一段代码

#include<iostream>
#include<unordered_map>
#include<deque>



        std::deque<int> freeIds;
        template <class T> std::unordered_map<int, T> storedObj;
            unsigned static int objIdCount=0;
        const unsigned long int MAXID = 1000000000;

你能告诉我哪里出了问题吗?谢谢

您正在执行 partial template specialisation 此处(参见 http://en.cppreference.com/w/cpp/language/partial_specialization)。可能您想到的是类似 typedef 的结构,但这不适用于模板。

通过部分模板特化,您可以(部分)重新实现或重新定义模板化类型。

实现目标的一种方法可能是:

template <class T>
class my_unordered_map :
    public std::unordered_map<int, T>
{
};

int main( void ) {
    my_unordered_map<float>  mf;

    return 0;
}

模板用于编译时多态性。如果不为该模板指定实际数据类型,则无法实例化基于模板的 class。

使用模板的基本方法是:

#include <iostream>
using namespace std;

template <class T>
class MyClass {
    T foo;
public:
    MyClass(T bar) {
        foo = bar;
    }
    void print() {
        cout << foo;
    }
};

int main() {
    MyClass<int> c(5);
    c.print(); // prints 5
    return 0;
}

您可以通过扩展(派生)unordered_map class 来实现您想要做的事情,如下所示:

#include <iostream>
#include <unordered_map>
using namespace std;

template <class T>
class MyClass: public unordered_map<int, T> {
    // optional extra code here
};

int main() {
    MyClass<string> cstring;
    cstring[0] = "foo";
    cout << cstring[0] << "\n"; // prints "foo"

    MyClass<double> cdouble;
    cdouble[0] = 3.14; // prints 3.14
    cout << cdouble[0];

    return 0;
}