Laschet Jain
Laschet Jain

Reputation: 744

Writing a comparator function for specific type within template class

I'm working with a library which has a template class and it stores a std::vector of all the template type passed to it.

I pass std::tuple<A, B, C*> to that template class (where A, B, C are classes I've implemented).

I want to add an additional line to that class in which I'll call std::sort on that std::vector. Is there any way to pass/implement a comparator operator to std::sort which works for that specific type?

First I thought of writing operator< for A, B, C but quickly realised that the third tuple parameter I pass is a pointer to C. And since pointer is not a user-defined type, I won't be able to overwrite the default operator.

I also, read about typename but I'm not clear with it's use and don't know if it is applicable here. Thanks.

Upvotes: 1

Views: 215

Answers (2)

Ap31
Ap31

Reputation: 3314

What you can do is add your own templated MyComparator<T> class, that would default to std::less<T> in all the cases except std::tuple<A,B,C*>:

template<typename T> struct MyComparator : public std::less<T>
{};

template<> struct MyComparator<std::tuple<A,B,C*>>
{
    // your own operator() here
};

And then just use that comprator in the std::sort inside of your template:

std::sort(std::begin(v), std::end(v), MyComparator<T>{});

Upvotes: 0

Jack
Jack

Reputation: 133567

Since you are dealing with a standard type it is not so nice to specialize a comparator for that type. It's more simple to define a custom comparator and use it when needed, eg:

#include <iostream>
#include <tuple>
#include <vector>
#include <algorithm>

using tuple_t = std::tuple<int, float, int*>;

int main() 
{
    auto comparator = [](const tuple_t& t1, const tuple_t& t2) 
    {
      if (std::get<0>(t1) == std::get<0>(t2))
        return *std::get<2>(t1) < *std::get<2>(t2);
      else
        return std::get<0>(t1) < std::get<0>(t2);
    };

    std::vector<tuple_t> data;
    std::sort(data.begin(), data.end(), comparator);
}

If you really find yourself calling std::sort a lot of times, or you want to provide the type with the required operator then maybe it's better to define a custom type instead that using std::tuple.

Upvotes: 2

Related Questions