STL中的ptr_fun

STL中的ptr_fun

       ptr_fun只是将一个普通的函数(或者函数指针)适配成类pointer_to_binary_function,而该类实际上是binary_function的子类,这样出来的functor就有利于同STL的算法等适配。 
      下面的例子就是说明了使用ptr_fun将普通的函数适配成bind1st或bind2nd能够使用的functor,否则对bind1st或bind2nd直接绑定普通函数,则编译出错。 

#include <algorithm>
#include <functional>
#include <iostream>

using namespace std;

int sum(int arg1, int arg2)
{
	cout<<"ARG 1: "<<arg1<<endl;
	cout<<"ARG 2: "<<arg2<<endl;

	int sum = arg1 + arg2;
	cout<<"SUM: "<<sum<<endl;

	return sum;
}

int main(int argc,char* argv[])
{
	bind1st(ptr_fun(sum),1)(2); // the same as sum(1,2)
	bind2nd(ptr_fun(sum),1)(2); //the same as sum(2,1)

	getchar();
	return 0;
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值