Parameter to use std::greater or std::less as argument

Qaz picture Qaz · Mar 28, 2014 · Viewed 8.1k times · Source

I would like to make a function with a parameter that accepts either std::greater<int> or std::less<int> as the argument. I'm stuck on the syntax for the parameter, though.

This is the format I tried:

myFunction(int a, int b, bool *comp(int, int)) { … }
…
std::greater<int> bigger;
myFunction(2, 3, bigger);

That doesn't work, though, and I suspect the third parameter is just completely wrong. What should it actually be?

cannot convert std::greater<int> to bool* (*)(int, int)

Answer

user1942027 picture user1942027 · Mar 28, 2014

Functions taking a comparator are usually implemented via templates:

template <typename Comparator>
myFunction(int a, int b, Comparator comp) { … }

but you could also use std::function to implement it:

myFunction(int a, int b, std::function<bool (int, int)> ) { … }

The first version exposes code in the header but will usually perform better. As for the second version, you can hide the implementation in the .cpp file, but you would lose some performance due to the impossibility to inline the comparator calls.