Operator [] overload to accept char * for index
I have the following code:
class IList{
public:
virtual const Pair *get(const char *key) const = 0;
inline const Pair *operator[](const char *key) const;
};
inline const Pair *IROList::operator[](const char *key) const{
return get(key);
}
the code compiles fine, but when I try to use it:
IList *list = (IList *) SomeFactory();
Pair *p;
p = list["3 city"];
I got:
test_list.cc:47:19: error: invalid types βIList*[const char [7]]β for array subscript
p = list["3 city"];
^
I can figure out if the index of the array is int or char, but then how does std :: map do char * / strings?
source to share
If yours is list
also a pointer, you cannot use the operator the []
way you did. This is because it is list["3 city"]
equivalent list.operator[]("3 city")
. If you specified a pointer, you would need to use list->operator[]("3 city")
or - which is more readable - (*list)["3 city"]
. Of course, you can also make your list a link and use normally:
auto& listRef = *list;
p = listRef["3 city"];
source to share