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?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
You could also use type traits. It will give you a framework to solve also the possible future differences between types.
You should factor out the comparison as a type, like the normal
std::map
does. That is, have a utility classless_compare
:And then:
And to compare two values, do:
if (mCompare(someThing, someOtherThing))
, which will be true withsomeThing
is "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_compare
class for C-strings. (And also providegreater_compare
and kin.)Do keep in mind, unless this is for learning, you should not be implementing your own map. Also note that
std::string
hasoperator<
overloaded already.