#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
// TEMPLATE STRUCT less
template<class _Ty = void>
struct my_less
{ // functor for operator<
typedef _Ty first_argument_type;
typedef _Ty second_argument_type;
typedef bool result_type;
constexpr bool operator()(const _Ty& _Left, const _Ty& _Right) const
{ // apply operator< to operands
return (_Left < _Right);
}
};
template<class Operation>
class my_binder2nd//仿函数适配器functor adapter
:public unary_function<typename Operation::first_argument_type, typename Operation::second_argument_type>
{
protected://两个数据成员
Operation op;//二元函数对象
typename Operation::second_argument_type value;
public:
//constructor
my_binder2nd(const Operation &obj, const typename Operation::second_argument_type &val) :op(obj), value(val) {}
typename Operation::result_type//函数返回类型
operator()(typename Operation::first_argument_type&x)const
{
return op(x, value);
}
};
template<class Operation, class T>
inline my_binder2nd<Operation>my_bind2nd(const Operation&op, const T&x)//仿函数适配器辅助函数(自己写一个my_bind2nd函数模板,目的是为了创建一个my_binder2nd的对象),主要是借助函数模板具有可以自动推导形参类型的功能
{
typedef typename Operation::second_argument_type agr2_type;
return my_binder2nd<Operation>(op, agr2_type(x));//调用my_binder2nd的constructor创建my_binder2nd的对象
}
int main()
{
vector<int>v = { 5,10,20,30,40,50 };
cout << count_if(v.begin(), v.end(), my_bind2nd(my_less<int>(), 40)) << endl;
cout << count_if(v.begin(), v.end(), my_bind2nd(my_less<int>(), 40.1)) << endl;
system("pause");
return 0;
}
重点:less<int>()
是二元谓词对象,my_bind2nd(less<int>(), 40)
是一元对象,又因为my_bind2nd中的二元函数对象更准确的来说是二元谓词对象,所以my_bind2nd(less<int>(), 40)
是一元谓词对象。