//算术类
template <class T>
struct plus : public binary_function<T, T, T> {
T operator()(const T& x, const T& y) const
{ return x + y; }
};
template <class T>
struct minus : public binary_function<T, T, T> {
T operator()(const T& x, const T& y) const
{ return x - y; }
};
//逻辑运算类
template <class T>
struct logical_and : public binary_function<T, T, T> {
T operator()(const T& x, const T& y) const
{ return x && y; }
};
//相对关系类
template <class T>
struct equal_to : public binary_function<T, T, T> {
T operator()(const T& x, const T& y) const
{ return x == y; }
};
template <class T>
struct less : public binary_function<T, T, T> {
T operator()(const T& x, const T& y) const
{ return x < y; }
};
可以看到所有标准库提供的functor都继承了binary_function,有的是unary_function,这些就是融入了STL的条件。
调用:
#include <iostream> // std::cout
#include <functional> // std::plus
#include <algorithm> // std::transform
using namespace std;
int main(void)
{
cout << minus<int>()(10,5) << endl;//5
cout << multiplies<int>()(10,5) << endl;//50
cout << divides<int>()(10,5) << endl;//2
cout << modulus<int>()(10,5) << endl;//0
cout << negate<int>()(10) << endl;//-10
return 0;
}
继承后的unary_function和binary_function占0字节,不占用内存,但赋予了仿函数一对typedef,继承了这些函数的仿函数叫做“可适配的仿函数”。当仿函数需要被适配时,适配器会问仿函数一些问题,只有继承了这些typedef的仿函数可以回答这些问题。
GNU C++独有的functors