I wonder if there is support in STL for this:
Say I have an class like this :
class Person
{
public:
int getAge() const;
double getIncome() const
I see that dribeas already posted that idea, but since I already wrote it, here's how you'd write a generic comparator to use getter functions.
#include
template
class CompareAttributeT: public std::binary_function
{
typedef ResultType (Object::*Getter)() const;
Getter getter;
public:
CompareAttributeT(Getter method): getter(method) {}
bool operator()(const Object* lhv, const Object* rhv) const
{
return (lhv->*getter)() < (rhv->*getter)();
}
};
template
CompareAttributeT
Usage:
std::sort(people.begin(), people.end(), CompareAttribute(&Person::getAge));
I think it might be a good idea to overload operator() for non-pointers, but then one couldn't typedef the argument_types by inheriting from binary_function - which is probably not a great loss, since it would hard to use it where those are needed anyway, for example, one just couldn't negate the comparison functor anyway.