C ++对象列表数组

时间:2017-06-16 20:06:09

标签: c++ arrays list templates object

我有一个班级KeyValuePair

template <typename T>
class KeyValuePair {
public:
    //Default constructor
    KeyValuePair() {}

    //Copy assignment operator
    KeyValuePair& operator=(const KeyValuePair& obj) {
        KeyValuePair temp;
        return temp;
    }

    //Copy constructor
    KeyValuePair(const KeyValuePair<T>& obj) {
        this->key = obj.key;
        this->value = obj.value;
    }

    //Move consturctor
    KeyValuePair(KeyValuePair<T>&& obj) {
        this->key = std::move(obj.key);
        this->value = std::move(obj.value);
    }

    //Constructor to copy L-values
    KeyValuePair(const string& key, const T& value) {
        this->key = key;
        this->value = value;
    }

    //Constructor to move R-values
    KeyValuePair(const string& key, T&& value) {

        this->key = key;
        this->value = std::move(value);
    }

    string key;
    T value;
};

我正在尝试制作一系列KeyValuePairs

列表
list<KeyValuePair<string, T>> *arr = new list<KeyValuePair<string, T>>[10000]

当我尝试制作列表数组时,我遇到两个错误:

  

KeyValuePair:模板参数太多

     

KeyValuePair:非专业化的课程模板不能用作   模板参数_Ty的模板参数,期望一个真实的类型。

关于如何让它发挥作用的任何想法?

1 个答案:

答案 0 :(得分:0)

template <typename T>
class KeyValuePair {
/*...*/

KeyValuePair的声明只需要一个模板参数。如果你期望它需要两个,你需要写这样的东西:

template <typename T, typename U>
class KeyValuePair {
/*...*/

或者,由于您的实现似乎假设所有键都是string,因此您可以从数组中删除string使用:

list<KeyValuePair<T>> *arr = new list<KeyValuePair<T>>[10000];