Yes. operator()
is called the "function call" operator, and allows an object to be usable as if it were a function. Such a class is called a "functor".
A common pattern is to make functors that compare two things for equality or relations, for use in anything requiring a comparison predicate. (This one could be usable in an std::map
, for example. It would have a member likecmp_decr_int2 compare;
and then it could compare the relation between two things with: if (compare(x, y)) /* x is less than y, by some metric */
)
This particular struct orders two peak2
's by comparing their int2
members. It could be better written as:
struct cmp_decr_int2
{
// note const! vvvvv
bool operator() (peak2 a, peak2 b) const
{
return a.int2 > b.int2;
}
};
The function should be const
because it does not need to change any members (there are none to change.) const
-correctness is important.*
In many cases these functors are used in contexts where the arguments themselves are const
, so you should either take the arguments by value as in the example or by constant reference.
You should prefer to pass types by const-reference over by-value, except when that type is fundamental (float, unsigned int, double, etc.) or smaller than a void*
. In most cases, then, you will pass by const-reference:
struct cmp_decr_int2
{
// note const&: vvvvv v vvvvv v vvvvv
bool operator() (const peak2 & a, const peak2 & b) const
{
return a.int2 > b.int2;
}
};
*If this were used as a predicate in a std::map
, for example, without const
the map wouldn't be able to compare two things while within a const
function.