Custom class as template parameter

I am implementing a custom STL map . I need to make sure that any datatype (main or custom) will work with it . I have declared the Map class as a template that has two parameters for a key and a value. My question is, if I need to use a string as a key type , how can I overload <and> only for operators like string <... In specialized specialization, we have to specialize the entire class with the type that we want as far as I understand it. Is there a better way to do this? What if I add a separate Key class and use it as the template type for Key?

Thanks!

+2


a source to share


2 answers


You must separate the comparison as a type, as a normal one does std::map

. That is, there is a utility class less_compare

:

template <typename T>
struct less_compare
{
    bool operator()(const T& pLhs, const T& pRhs) const
    {
        return pLhs < pRhs;
    }
};

      

And then:

template <typename Key, typename Value, typename Compare = less_compare<Key> >
class map
{
    // ...

private:
    Compare mCompare;
};

      



And to compare two values, do:, if (mCompare(someThing, someOtherThing))

which will be true with someThing

, will be "less" someOtherThing

. Note that factoring also allows you to define custom comparisons (therefore "less" is specified). This is called political design.

And now you can only specialize the class less_compare

for C strings. (And also provide greater_compare

relatives.)


Keep in mind, if this is not for training, you should not implement your own map. Also note what it std::string

already has operator<

.

+1


a source


You can also use type properties . This will give you a basis for resolving possible future differences between types as well.



0


a source







All Articles