Defining a function object "more" in C ++
template <class T> struct greater : binary_function <T, T, bool> {
bool operator() (const T& x, const T& y) const {
return x > y;
}
};
I found this definition of the "Object object to compare more than inequality" class in the STL library. Can someone please explain to me how this code works and compiles?
template <class T> // A template class taking any type T
// This class inherit from std::binary_function
struct greater : binary_function <T, T, bool>
{
// This is a struct (not a class).
// It means members and inheritens is public by default
// This method defines operator() for this class
// you can do: greater<int> op; op(x,y);
bool operator() (const T& x, const T& y) const {
// method is const, this means you can use it
// with a const greater<T> object
return x > y; // use T::operator> const
// if it does not exist, produces a compilation error
}
};
here is the definition std::binary_function
template <class Arg1, class Arg2, class Result>
struct binary_function {
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};
this allows you to access the types defining the binary_function function
greater<int> op;
greater<int>::result_type res = op(1,2);
which is equivalent
std::result_of<greater<int>>::type res = op(1,2);
This is a template class that can be created with a single type argument. So you can say greater<int>, greater<my_class>etc. Each of these instances has an operator (), which takes two type arguments const T&and returns the result of their comparison.
greater<int> gi;
if (gi(1, 2)) {
// won't get here
} else {
// will get here
}
, .
:
struct greater {
bool operator()(const int& x, const int& b) const {
return x > y;
}
greater g;
g(2,3); // returns false
g(3,2); // returns true
So functors perform a function in which you could also implement bool g (int x, int y) {return x> y;} and use it in the same way.
The good thing about functors is that you can store some data while working on a more complex data structure.
Then there is part of the template: you want to write the same functor for any type, you do not care if the type is int, float, complexe object, the code will be the same. This is part of the template for.