Q:

Overloading [ ] with a template type

I have a class that takes 2 template types, one for key (K) and one for value (V).
When trying to overload square brackets, I get an error saying "no operator "[]" matches these operands.
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;
            }
        }
    }
};

Then when trying to use it in main...
MyMap<string, int>* myMap = new MyMap<string, int>();  

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

I have read a lot of other solutions where they know the type for the key, but is it possible to use a template type of a key when overloading like this?
Thanks :)

A:

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

myMap here is a pointer. You meant:
cout << (*myMap)["hello"] << endl;

As oisyn noted, operator[] must be made public as well.

Also:

Don't use raw new/delete. Use smart pointers.

Actually, you probably don't need to allocate. Just create the map on the stack.

You're unnecessarily copying the key in your operator[]. Take it by const&.

