云起工作室 15711107967
03-51cto-仿函数
2023-01-29 17:09:11

一元函数

unary_function<argument_type,result_type>

二元函数

binary_function<first_argument_type,second_argument_type,result_type>


int res = plus<int>()(4,2) 加法 4+2

int res = minus<int>()(4,2) 减法 4-2

int res = multiplies<int>()(4.2) 乘法 4*2

int res = divides<int>()(4,2) 除法 4/2

int res = modulus<int>()(4,2) 取模 4%2

int res = negate<int>()(4) 取负数


bool res = equal_to<int>()(4,2) 等于

bool res = not_equal_to<int>()(4,2) 不等于

bool res = less<int>()(4,2) 小于

bool res = less_equal<int>()(4,2) 小于等于

bool res = greater<int>()(4,2) 大于

bool res = greater_equal<int>()(4,2) 大于等于


binder1st<less<int> > bd1( less<int>(), 3); 绑定第一个函数,即初始化时 3 是方法 less 的第一个参数

cout<< bd1(2) << endl; 打印 0

cout<< bind1st( less<int>(),3)(2) <<endl;


binder2nd<less<int> > bd2( less<int>(), 3); 绑定第二个函数,即初始化时 3 是方法 less 的第二个参数

cout<< bd2(2) << endl; 打印 1

cout << bind2nd( less<int>,3)(2) <<endl;


binder1st 的原理是

template<class Fn,class Ty>

struct bd1{

Fn function;

Ty can1;

bd1(const Fn & fun,const Ty &arg)

:function(fun),can1(arg){}

bool operator ()(Ty can2){

return function(can1,can2);

}

}