I want to create a class in c++. This class must manage with a collection. OK, no problem, I would like to use operator[] of course but, in this case, my wish is to index not by position, but by name ==> that means using a string indexer.
It seems that something of this kind is not so nice to my compiler:
// In hpp
class myclass {
...
...
std::string operator[](const std::string& name);
}
// In cpp
std::string myclass::operator[](const std::string& name) {
...
}
// In main
myclass m;
std::string value = m["Name"];
Compiler tells me that he cannot solve this because operator[const char[5]] does not exists. OK OK I could figure this... Compiler thinks that by calling m["Name"] I'm trying to call an operator admitting a char* and not a string... ok Let's change the code with operator[] allowing a char* as parameter... nothing.
Can somebody tell me how to achieve such a result in c++ in a best practice way? I suppose that is a common problem to index by string and not by integer... Thank you.
std::string value = m[std::string("Name")];
– SingleNegationElimination