Template completed by operator

Can you use templates (or the like) in C ++ to indicate which operation is performed in a function?

I don’t know how to explain this more clearly, so I will show you how this could be (but not done) in the code:

template <operator OPERATION> int getMaxOrMin(int a, int b) { return a OPERATION b ? a : b; } 

where finding the maximum or minimum of a or b will be (this is where my pseudo-syntax gets a little confused, carry me):

 int max = getMaxOrMin< > > (a, b); int min = getMaxOrMin< < > (a, b); 

I know that it’s not how to do it at all (because it doesn’t even make sense syntactically), but I hope this clarifies the type of thing I want to do.

The reason for me is that I am doing a PriorityQueue implementation, and it would be nice to easily switch between a base, which is a maximum heap or a mini-heap on the fly, without copying and pasting the code to make two different classes.

I know that I could do this with a macro, but the only way I knew how to do this would give me either the maximum heap or the mini-heap, but not both in the same compilation. I probably don't notice the way.

+4
source share
2 answers

Yes, but you need to define it as a functor:

 template <typename OPERATION> int getMaxOrMin(int a, int b) { OPERATION operation; return operation(a, b) ? a : b; } 

Now you can use it as follows:

 struct myLess { bool operator()(int a,int b) const { return a < b; } } struct myGreat { bool operator()(int a,int b) const { return a > b; } } void code() { int x = getMaxOrMin<myLess>(5,6); int y = getMaxOrMin<myGreat>(5,6); } 

It seems like a lot of work. But there are many predefined functors in the standard. On this page, scroll down to β€œ6: Function Objects”.
For your situation there are:

 std::less std::greater 

So the code becomes:

 template <typename OPERATION> int getMaxOrMin(int a, int b) { OPERATION operation; return operation(a, b) ? a : b; } void codeTry2() { int x = getMaxOrMin<std::less<int> >(5,6); int y = getMaxOrMin<std::greater<int> >(5,6); } 
+2
source

Do what std::map and friends do: execute a comparison function / functor as a template parameter. See std::less and std::greater .

Remember that the standard library already has a well-developed and debugged priority queue, which you can use with an arbitrary comparison function.

+8
source

Source: https://habr.com/ru/post/1344807/