I’ m re-implementing std::map. I need to make sure that any data type (basic or user defined) key will work with it. I declared the Map class as a template which has two parameters for the key and the value. My question is if I need to use a string as the key type, how can I overload the < and > operators for string type keys only?? In template specialization we have to specialize the whole class with the type we need as I understand it.
Is there any way I can do this in a better way?? What if I add a separate Key class and use it as the template type for Key?
I’ m re-implementing std::map . I need to make sure that any data type
Share
You should factor out the comparison as a type, like the normal
std::mapdoes. That is, have a utility classless_compare:And then:
And to compare two values, do:
if (mCompare(someThing, someOtherThing)), which will be true withsomeThingis “less than”someOtherThing. Note this factoring also allows user-defined comparisons (which is why “less than” is quoted). This is known as policy-based design.And now you can specialize just the
less_compareclass for C-strings. (And also providegreater_compareand kin.)Do keep in mind, unless this is for learning, you should not be implementing your own map. Also note that
std::stringhasoperator<overloaded already.