二元成员函数适配器

自己实现的二元成员函数适配器,专门用于调用类成员函数
我们实现的适配器必须要有指向成员函数的指针,一般而言,定义指向成员函数的指针格式为:T3 (T1::*fun)(T2),qizhong T3表示返回值类型,T1表示类类型,T2表示函数参数类型。
// ConsoleApplication49.cpp : 定义控制台应用程序的入口点。
//用于成员函数指针的适配器--将成员函数当作放函数使用
/*
   对于适配器而言,适配器本身内部有指向所调用实体的指针
*/
#include "stdafx.h"
#include
#include
#include
#include
#include
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 contain_mem_fun_t:public binary_function{
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 contain_mem_fun(T3(T1::*pf)(T2)){
	return contain_mem_fun_t(pf);
}
int _tmain(int argc, _TCHAR* argv[])
{
	list lst;
	lst.push_back(2);
	lst.push_back(3);
	/*list::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
	  inputiterator  for_each(inputstream input,inputerator output,op operator)
	    {
		      for(;input!=output;input++){
			       op(input);
			  } 
			  return input;
		}
	
	*/
	system("pause");
	return 0;
}
二元成员函数适配器_第1张图片

你可能感兴趣的:(c++)