Home > Software engineering >  Template arguement for comparator when passing priority queue to a function
Template arguement for comparator when passing priority queue to a function

Time:02-02

I am new to C and still learning the concepts. I am trying to pass a priority queue with custom comparators to a templated function. I want to abstract the comparator type in priority queue template argument list when I pass it to the function in the function definition. Below is an example of what I am trying to do.

File1.h

struct my_comparator
{
bool operator()(const some_type* c1, const some_type* c2){
c1->property < c2->property;
}
another_funtion(….)
{
std::priority_queue<const some_type*, std::vector<const some_type*>, my_comparator> my_queue;

some_function(my_queue);
}
File2.h

some_function(std::priority_queue<const some_type*, std::vector<const some_type*>, comparator_type> queue_)
{
//implementation
}

I want to understand what to pass as the comparator type in the priority queue template of some_function definition, such that it can accept any custom comparator I define (adhering to the required format), in the file that is calling the function (which is File1.h in this case).

P.S: This is my first time posting here. Apologies in advance for any format mistakes.Thank you!

CodePudding user response:

You can go all the way to make some_function generic to accept any type:

template <typename P>
void some_function(P queue_)
{
    //implementation
}

(see also the example here: https://en.cppreference.com/w/cpp/container/priority_queue) or use an alias

using priority_queue_type = std::priority_queue<const some_type*, std::vector<const some_type*>;

and make that available in both headers.

CodePudding user response:

It seems that you want to allow any comparator (on your custom type some_type) to be used. To that effect, you can simply use (I'm assuming that you indeed want to passs by value) :

template<class TComparator>
void some_function(std::priority_queue<const some_type*, std::vector<const some_type*>, TComparator> queue) 
{ 
  // ... 
}

Then, let the compiler deduce your argument. Let say that you have two comparators my_comp1 and my_comp2, then you can have :

template<class TComparator>
using my_queue_t = std::priority_queue<const some_type*, std::vector<const some_type*>, TComparator>;

my_queue_t<my_comp1> q1;
my_queue_t<my_comp2> q2;

// Do something with them
some_function(q1);
some_function(q2);

The comparator type will be automatically deduced by the compiler. You can also have the template alias be separated to another file (near your type some_type for instance) and be used in both files.

  •  Tags:  
  • Related