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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With