After writing out the main functionality for my templatized data structure, I am stumbling with the syntax to allow for Compare (so the user can provide a definition for less). If I am not mistaken, I need to add at least another constructor. I tried reading the STL implementations for priority_queue and the such, but the syntax looked rather cryptic. Can someone please either point me in the direction of decent documentation (since I cannot seem to find any) or provide me with instructions?

I could be mistaken, though I believe that the STL sorted containers expect a type with a valid operator<. If the type doesn't provide one, then overloaded constructor(s) will take an additional parameter in the form of a compare function, or a function object which overloads operator() instead.

Since you don't know the precise type of the comparator in advance, you need to provide a templated constructor where any kind of comparator can be used to compare objects within the data structure


Here's a brief example of a constructor accepting a functor, whose type is determined at compile time.

/* less_comparator - user-defined comparison */
template <typename T>
struct less_comparator
{
    bool operator()(T, T) const;
};

template <typename T>
bool less_comparator<T>::operator() (T lhs, T rhs) const
{
    return lhs < rhs;
}

template<typename T>
class structure
{
public:
    structure() {}
    template<class Comparator>
    structure( Comparator comp )
    {
    }
};

int main()
{
    structure<int> s( less_comparator<int> );
}

Additional:

It seems I was half-right, although, the STL uses the std::less<T> functor class as its default predicate for sorted containers, as found in the <functional> header. (std::less in turn assumes that operator< is available)

The STL also takes the extra step of enforcing the predicate to match a certain type (Which the example I gave doesn't do), using an additional template parameter, which defaults to std::less<T>. This is presumably a safety net to stop predicates for different types being used accidentally.

I ended up using the std::less<T> functor, which worked perfectly for my implementation. Thank you very much, Bench!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.