一.定义
仿函数是类中定义了一个含有operator ()成员函数的对象,可以将它视为一般的函数,它有着快捷调用的功能——通过仿函数地址调用,其次,它相比一般函数可以传入模板参数,适配与各种模板的使用中。
二.使用
1.作为类的模板参数适配于各种模板类的调用
最常见的就是比较大小,在优先级队列priority_queue中就有仿函数less和greater,以下代码模拟实现两种仿函数的功能:
// 仿函数比较
template<class T>
class Less
{
public:
bool operator()(const T& a, const T& b)
{
return a < b;
}
};
template<class T>
class Greater
{
public:
bool operator()(const T& a, const T& b)
{
return a > b;
}
};
将模板类设置为与调用类中的模板类型相同,可以达到比较大小的效果,同时如果我们将priority_queue传入不同的仿函数,将有不同的效果——默认仿函数为less,传入greater则可以达到建大堆的效果。
template<class T, class Container = vector<T>, class cmp = Less<T>>
class priority_queue
2.自定义仿函数
有的情况下我们必须要自定义仿函数,比如如果我们传入的模板类型为自定义类型的指针;此处拿日期类作为例子:如果继续使用上述的仿函数比较,那么最终比较的将是日期类的指针优先级,显然,这是毫无意义的。
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
: _year(year)
, _month(month)
, _day(day)
{}
bool operator<(const Date& d)const
{
return (_year < d._year) ||
(_year == d._year && _month < d._month) ||
(_year == d._year && _month == d._month && _day < d._day);
}
bool operator>(const Date& d)const
{
return (_year > d._year) ||
(_year == d._year && _month > d._month) ||
(_year == d._year && _month == d._month && _day > d._day);
}
friend ostream& operator<<(ostream& _cout, const Date& d);
private:
int _year;
int _month;
int _day;
};
ostream& operator<<(ostream& _cout, const Date& d)
{
_cout << d._year << "-" << d._month << "-" << d._day;
return _cout;
}
此时我们可以自定义该类的仿函数如下:
// 自定义仿函数
struct LessPDate
{
// struct结构体默认权限为public
bool operator()(const Date* p1, const Date* p2)
{
return *p1 < *p2;
}
};