template<class T>struct is_less :public binary_function<T, T, bool>
{
is_less() { cout << "less构造函数" << endl; }
bool operator()(const T & left, const T & right) { cout << "less operator()" << endl; return (left < right); };
};
//一元绑定
template<class _class>struct binder1st:public unary_function<typename _class::second_argument_type,typename _class::result_type>
{
public:
//binder1st(less<int>(),5){}
binder1st(const _class & cs, typename _class::first_argument_type _first) :object(cs), first(_first)
{
cout << "binder1st 构造函数" << endl;
}
typename _class::result_type operator()(typename _class::second_argument_type _second)
{
cout << "binder1st operator()" << endl;
return object(first, _second);//第一个参数默认,第二个参数可设置
//binder1st(less<int>(),5){}->//less<int>object(first,second);??
}
private:
_class object;
typename _class::first_argument_type first;
};
template<class _class,class T>binder1st<_class> bind1st(const _class & object,const T & value)
{
//之所以要再起别名,就是为了避免二义性,你不知道_class::first_argument_type是函数还是类型
using first_arg = typename _class::first_argument_type;//声明为类型
//return binder1st<_class>(object, typename _class::first_argument_type(value));//这样写可读性不太好,但还是可以的
return binder1st<_class>(object, first_arg(value));
}
template<class T, class Pred>int Count_if(const T * first, const T * last, Pred pred)
{
int ret = 0;
for (; first != last; first++)
{
if (pred(*first))
{
ret++;
}
}
return ret;
}
int main()
{
int numbers[] = { 1,2,3,4,5,6 };
int cx;
//这里先调用less<int>构造函数 ,再调用bind1st构造函数 ,但是bind1st operator()是怎么被调用的搞不懂
cx = Count_if(numbers, numbers + 6, bind1st(is_less<int>(), 5));
cout << "有 " << cx << " 个数大于5\n";//1
return 0;
}
//运行的结果
|
|