使用模板类型重载[]

时间:2017-11-27 16:20:23

标签: c++ templates dictionary

我有一个类,它有2个模板类型,一个用于键(K),一个用于值(V)。

当试图超过方括号时,我收到错误说"没有操作符" []"匹配这些操作数。

template <typename K, typename V>
class MyMap
{
    KeyPair<K, V>* Pairs;
    int Count = 0;

public:
    MyMap()
    {
        Pairs = new KeyPair<K, V>[100];
    }

    V& operator[] (const K& key)
    {
        for (int i = 0; i < Count; ++i)
        {
            if (key == Pairs[i].Key)
            {
                return Pairs[i].Value;
            }
        }
    }
};

然后尝试在主...中使用它时

MyMap<string, int>* myMap = new MyMap<string, int>();  

// This gives me a "no operator "[]" matches these operands.
cout << myMap["hello"] << endl;

我已经阅读了很多其他解决方案,他们知道密钥的类型,但是在重载时是否可以使用密钥的模板类型?

谢谢:)

0 个答案:

没有答案