Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems overloading [] operator with a template class

I'm having problems overloading the subscript operator with a template class in c++. I have a custom map class implementation and I need to be able to access the elements via the key.

template <typename K, typename DT>
DT& myMap<K, DT>::operator[](K key)
{
  for (int i = 0; i<size; i++)
 {
    if (elements[i].key == key){
        return elements[i].data;
    }
 } 
}

Is how I'm trying to overload the operator at the moment. The compiler doesn't accept the K key to search for the data. K being the data type for the key. This is stored in a separate class that the myMap class contains in an array.

So if in main I try to do:

myMap<string, int> * test = new myMap < string, int > ;
test["car"] = 50;

It says:

Error expression must have an integral or unscoped enum type

I'm not quite sure what the problem is.

like image 639
Ash M Avatar asked Nov 20 '14 13:11

Ash M


1 Answers

test is a pointer to MyMap, not an object thereof, so test["car"] is calling the built-in dereference operator, not your overload.

You need (*test)["car"] or test->operator[]("car") to make it work.

like image 172
jrok Avatar answered Nov 01 '22 21:11

jrok