#include <functional>
unary_function
// STL 规定,每一个Adaptable(可配接的) Unary Function 都应该继承此类别 template <class Arg, class Result> struct unary_function { typedef Arg argument_type; typedef Result result_type; }
binary_function
// STL 规定,每一个 Adaptable 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; }
greater<>/less<>
// 大的在前,小的在后,也即在排序时,逆序输出
template<typename T>
struct greater :public binary_function<T, T, bool>
{
result_type operator()(const first_result_type& left, const second_result_type& right) const
{
return left > right;
}
}
如果我们要实现一个绝对值大的在前,绝对值小的在后,也即比较的是绝对值的大小。
template<typename T>
struct abs_greater :public binary_function<T, T, bool>
{
bool operator()(const T& left, const T& right) const
{
return abs(left) > abs(right);
}
}
排序准则(sorting criterion)
或许因为不想,或许因为不能,无法使用一般的 operator<
对这些对象排序,而是必须以某种特定的规则(通常基于某些成员函数)来排序,此时便是 function objects 施展身手的舞台;
class Person
{
public:
std::string firstname() const;
std::string secondname() const;
...
}
class PersonSortCriterion
{
public:
bool operator() (const Person& left, const Person& right) const
{
return left.lastname() < right.lastname() ||
(left.lastname() == right.lastname() && left.firstname() < right.firstname());
}
}