二元成员函数适配器

自己实现的二元成员函数适配器,专门用于调用类成员函数
我们实现的适配器必须要有指向成员函数的指针,一般而言,定义指向成员函数的指针格式为:T3 (T1::*fun)(T2),qizhong T3表示返回值类型,T1表示类类型,T2表示函数参数类型。
// ConsoleApplication49.cpp : 定义控制台应用程序的入口点。
//用于成员函数指针的适配器--将成员函数当作放函数使用
/*
   对于适配器而言,适配器本身内部有指向所调用实体的指针
*/
#include "stdafx.h"
#include<functional>
#include<iostream>
#include<string>
#include<list>
#include<queue>
using namespace std;
class student{
public:
	student(int iid) :id(iid){
		count++;
	};
	void diaplay(){
		cout << "第" << count << "个学生" << "student: " << id << endl;
	}
	void  reset_id(int x){
		//id = x;
		cout << "student: " << x<< endl;
		
	}
	void get_id(){
		cout << "student: " << id << endl;

	}
private:
	int id;
	static int count;
};
int student::count = 0;
template<class T1, class T2, class T3>
class contain_mem_fun_t:public binary_function<T1,T2,T3>{
public:
	contain_mem_fun_t(T3 (T1::*pf)(T2)) :f(pf){}
	T3 operator()(T1 g,T2 x) const{
		return (g.*f)(x);
	}
protected:
	T3 (T1::*f) (T2);//定义成员函数

};
template< class T1, class T2, class T3>
inline contain_mem_fun_t<T1, T2, T3> contain_mem_fun(T3(T1::*pf)(T2)){
	return contain_mem_fun_t<T1, T2, T3>(pf);
}
int _tmain(int argc, _TCHAR* argv[])
{
	list<student> lst;
	lst.push_back(2);
	lst.push_back(3);
	/*list<student>::iterator iter;
	for (iter = lst.begin(); iter != lst.end(); iter++){
		iter->diaplay();
	}*/
	for_each(lst.begin(), lst.end(), bind2nd(contain_mem_fun(&student::reset_id), 7));
	/*  template<class inputiterator>
	  inputiterator  for_each(inputstream input,inputerator output,op operator)
	    {
		      for(;input!=output;input++){
			       op(input);
			  } 
			  return input;
		}
	
	*/
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值