Overload Issues [] with Template Class

I'm having problems overloading the index operator with the template class in C ++. I have a custom implementation of the map class, and I need to have access to the elements through 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; } } } 

I am trying to overload the operator at the moment. The compiler does not accept the K key to search for data. K is the data type for the key. This is stored in a separate class, which the myMap class contains in the array.

So, if basically 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.

+5
source share
2 answers

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

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

+5
source

Your mistake is that you are using a pointer to MyMap instead of the object itself. Instead

 myMap<string, int> * test = new myMap < string, int > ; (*test)["car"] = 50 // works but is not idiomatic C++ // ... delete test; // don't forget! 

you should use

 auto test = myMap<string, int>{}; // or: myMap<string, int> test = myMap<string, int>{}; test["car"] = 50 

If you really need to use pointers, you should at least use smart pointers:

 auto test_ptr = std::make_unique<myMap<string, int>>(); // or: std::unique_ptr<myMap<string, int>> test_ptr = std::make_unique<myMap<string, int>>(); (*test)["car"] = 50; 
0
source

Source: https://habr.com/ru/post/1207303/


All Articles