Search code examples
c++comparisoncontainersfunction-object

std::set - like function object support in my container


I have implemented my own container:

template<typename T>
class MyContainer
{
    // body where in some point 2 elements of collection are compared (-1, 0 and 1 possible comparison results)
};

What I want to do is add support of function objects, just like in std::set, where it is possible to do function object like this:

struct Comparator
{
    bool operator()(const char* s1, const char* s2) const
    {
        return strcmp(s1, s2) < 0;
    }
};

and then pass it as set parameter:

std::set<const char*, Comparator> SomeSet;

I'm not every-day C++ programmer, so I need help to achieve that. What must I do in order to add support to this? Must I create field in MyContainer in order to store function object in it to use it in my sorting methods inside container?


Solution

  • I resolved it by adding default template value, and defining default comparing class:

    template<typename T, class Compare = DefaultTreeOrder<T>>
    class MyContainer
    {
        private:
            Compare compare;
        public:
            MyContainer()
            {
                compare = Compare();
            }
    };
    

    where DefaultTreeOrder is:

    template<typename T>
    class DefaultTreeOrder 
    {
        public:
            int operator()(T value1, T value2)
            {
                less<T> l;
                greater<T> g;
    
                if(l(value1, value2))
                {
                   return 1;
                }
                else if(g(value1, value2))
                {
                    return -1;
                }
    
                return 0;
            } 
    };