C++中的代码重用(六)

成员模板 

//example.h
#ifndef _EXAMPLE_H_
#define _EXAMPLE_H_
/*模板类和模板函数一样也存在隐、显式实例化以及显式实例化,部分具体化*/
/*模板成员*/
#include<iostream>
template<typename T>
class Example
{
private:
	template<typename V>
	class child
	{
	private:
		V data;
	public:
		child(){};
		child(V d) :data(d){}
		V & getd(){ return data; }
		void show()const{ cout << "Child data=" << data << endl; }
	};
	child<T>temp1;
	child<int>temp2;
public:
	Example(){}
	Example(T d, int i) :temp1(d), temp2(i){}
	template<typename U>
	U func(U u, T t){ return ((temp2.getd() + temp1.getd()))*u / t; }
	void show(){ temp1.show(); temp2.show(); }
};
#endif //_EXAMPLE_H_

//main.cpp
/**
*Copyright U+00A9 2018 XXXXX. All Right Reserved.
*Filename:
*Author:XXXX
*Date:2018.12.15
*Version:VS 2013
*Description:
**/

#include<iostream>
//#include<cstdlib>
#include"windows.h"
#include"example.h"
using namespace std;
int main()
{
	Example<double>test(3.5, 2);
	cout << "test.show():\n";
	test.show();
	cout << "test.func(3.5, 2.3)=" << test.func(3.5, 2.3) << endl;
  system("pause");
  return 0;
}

对于成员模板也可以写成以下形式:

#ifndef _EXAMPLE_H_
#define _EXAMPLE_H_
/*模板类和模板函数一样也存在隐、显式实例化以及显式实例化,部分具体化*/
/*模板成员*/
#include<iostream>
using namespace std;
template<typename T>
class Example
{
private:
	template<typename V>
	class child;
	child<T>temp1;
	child<int>temp2;
public:
	Example(){}
	Example(T d, int i) :temp1(d), temp2(i){}
	template<typename U>
	U func(U u, T t);
	void show(){ temp1.show(); temp2.show(); }
};

template<typename T>
template<typename V>
class Example<T>::child
{
private:
	V data;
public:
	child(){};
	child(V d) :data(d){}
	V & getd(){ return data; }
	void show()const{ cout << "Child data=" << data << endl; }
};

template<typename T>
template<typename U>
U Example<T>::func(U u, T t)
{ 
	return ((temp2.getd() + temp1.getd()))*u / t; 
}
#endif //_EXAMPLE_H_

猜你喜欢

转载自blog.csdn.net/weixin_43871369/article/details/85013855