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.
It should work fine. See this example which compiles and works ok for me:
And I see no reason it should not, since std::string has implicit constructor taking
const char*
so the conversion should be automatic.Edit: From the comment it seems your problem was with your main beeing like this:
The reason:
The code that you have provided should compile okay (providing the
operator
ispublic
and you terminate yourclass
declaration with a;
). I suspect the compiler error is somewhere else.Personally, I would use
std::map<std::string, std::string>
as the container class.