在stl的泛型算法中,functor应用甚多。
template <typename T>
struct plus
{
T operator ()(const T& x, const T& y) { return x + y; }
};
template <typename T>
struct minus
{
T operator ()(const T& x, const T& y) { return x - y; }
};
void test()
{
plus<int> plusObj;
minus<int> minusObj;
cout << plusObj(32, 45) << endl;
cout << minusObj(32, 45) << endl;
cout << plus<int>()(32, 45) << endl;
cout << minus<int>()(32, 45) << endl;
}
在泛型算法中,应用甚多的是后面的那种“匿名对象”,因为很多algorithm中,匿名对象的生命周期在算法中,出了算法后匿名对象销毁。
举例:
传递的都是functor的匿名对象。
functor,说白了就是对operator()的重载