1. 程式人生 > >C++中的程式碼重用(七)=>模板友元

C++中的程式碼重用(七)=>模板友元

對於模板的友元一般分為三種:

1.非模板友元

2.約束模板函式

3.非約束模板函式

例子如下所示

//class_friend.h
#ifndef CLASS_FRIEND_H
#define CLASS_FRIEND_H
/*非模板友元*/
#include<iostream>
using namespace std;
template<typename U> void cnt();/***********1.約束模板友元函式先宣告********************/
template<typename U>void show_object(U &);

template<typename T>
class AC
{
private:
	T data;
	static int count;
public:
	AC(){}
	AC(const T &d) :data(d){ ++count; }
	~AC(){ --count; }
	/*非模板友元函式*/
	friend void get_count();//所有模板例項化的友元
	friend void show(AC<T>&object);//不是模板函式,只是將模板作為引數,必須顯式具體化定義
	/*約束模板友元函式*/
	friend void cnt<T>();/*2.宣告為模板友元*/
	friend void show_object</*AC<T>*/>(AC<T> &ac);
	/*非約束模板友元函式*/
	template<typename T1, typename T2>friend void show_(T1 &t1, T2 &t2);
};
template<typename T>
int AC<T>::count = 0;

void get_count()
{
	cout << "int count: " << AC<int>::count << "; ";
	cout << "double count: " << AC<double>::count << endl;
}
/*必須顯示具體化相應的型別*/
void show(AC<int> &object)
{
	cout << "AC<int>: " << object.data << endl;
}

void show(AC<double> &object)
{
	cout << "AC<double>: " << object.data << endl;
}

/*3.為約束模板友元定義*/
template<typename U>
void cnt()
{
	cout << "template size: " << sizeof(AC<U>) << "; ";
	cout << "template count<U>(): " << AC<U>::count << endl;
}

template<typename U>
void show_object(U &ac)//注意不可寫成void show_object<>(AC<U> &ac),與模板宣告處相一致
{
	cout << "data: " << ac.data << endl;
}

/*非約束模板友元函式定義*/
template<typename T1, typename T2>
void show_(T1 &t1, T2 &t2)
{
	cout << "T1.data: " << t1.data << ",T2.data: " << t2.data << endl;
}
#endif //CLASS_FRIEND_H

//main.cpp
#include<iostream>
//#include<cstdlib>
#include"windows.h"
#include"class_friend.h"
using namespace std;
int main()
{
	cout << "************非模板友元測試************\n";
	AC<int>obj1(10);
	get_count();//非模板友元函式
	AC<double>obj2(12.0);
	get_count();
	show(obj1);//非模板友元函式
	show(obj2);
	cout << "************約束模板友元測試**********\n";
	AC<int>obj3(5);
	AC<double>obj4(8.0);
	cout << "show_object(obj3): ";
	show_object(obj3);
	cout << "show_object(obj4): ";
	show_object(obj4);
	cout << "cnt<int>(): ";
	cnt<int>();
	cout << "cnt<double>(): ";
	cnt<double>();//注意呼叫格式
	cout << "************非約束模板友元測試********\n";
	cout << "show_(obj3, obj4): ";
	show_(obj3, obj4);
	cout << "Done!" << endl;
  system("pause");
  return 0;
}

程式執行結果如下