A Beginners guide to Templates

Function Template…

从一个不同类型的数组中查找最小元素,采用函数模板的形式。

template<class ElemType>
ElemType calcmin(ElemType elemField[],int iFieldSize)
{
	int iMin = 0;
	for (int i = 1; i < iFieldSize; i++)
	{
		if (elemField[i] < elemField[iMin])
		{
			iMin = i;
		}
	}
	return elemField[iMin];
}

该模板用于对两个不同类型的数组int[]和double[],查询最小值…

void LetsTestTheFunctionTemplate()
{
	int iField[] = {1,2,3,4,5,6};
	double dField[] = {2.5,2.31,10.23,15.2};

	int iSize1 = sizeof(iField)/sizeof(int);
	int i =calcmin(iField,iSize1);
	cout<<"i = "<<i<<endl;

	int iSize2 = sizeof(dField)/sizeof(double);
	double d = calcmin(dField,iSize2);
	cout<<"d = "<<d<<endl;
}

Class Template…

定义类模板和定义函数模板基本一样,定义一个普通类型的堆栈模板类操作不同的类型元素的堆栈。

template <typename ElemType, int iSize = 100>
class Stack{
public:
	Stack();
	~Stack(){};
	void push(const ElemType& anElement);
	void pop(ElemType& anElement);
	bool wasError() const;
	bool isEmpty() const;
private:
	ElemType elems[iSize];
	int iTop;
	bool bErrorOccd;
};

和实现普通的类一样,只是有一些稍微的不同,每次实现函数都需要添加<和>,并且需要模板类的名字不需要参数…

//构造函数
template <class ElemType, int iSize>
Stack<ElemType, iSize>::Stack():iTop(0),bErrorOccd(false)
{

}
//push函数实现…
template <class ElemType, int iSize>
void Stack<ElemType, iSize>::push(const ElemType &anElement)
{
	bErrorOccd = (iTop == iSize);
	if (!bErrorOccd)
	{
		elems[iTop++] = anElement;
	}
}
//pop函数实现
template<class ElemType, int iSize>
void Stack<ElemType, iSize>::pop(ElemType& anElement)
{
	bErrorOccd = (iTop == 0);
	if (!bErrorOccd)
	{
		anElement = elems[--iTop]; 
	}
}
//wasError函数实现
template<class ElemType, int iSize>
bool Stack<ElemType,iSize>::wasError()const
{
	return bErrorOccd;
}
//isEmpty函数实现
template<class ElemType, int iSize>
bool Stack<ElemType, iSize>::isEmpty() const
{
	return (iTop == 0);
}
//The Test code in main…
int _tmain(int argc, _TCHAR* argv[])
{
	LetsTestTheFunctionTemplate();

	Stack<int> iTheIntStack;
	for (int i = 0; i < 10; i++)
	{
		iTheIntStack.push(i);
	}
	while(!iTheIntStack.isEmpty())
	{
		int data;
		iTheIntStack.pop(data); 
		cout<<data<<" ";
	}
	cout<<endl;
	
	Stack<double,30>dTheDoubleStack;
	double d = 0.1;
	for (int i=0; i < 30; i++)
	{
		dTheDoubleStack.push((double)i+d);
	}
	while (!dTheDoubleStack.isEmpty())
	{
		double data;
		dTheDoubleStack.pop(data);
		cout<<data<<" ";
	}
	cout<<endl;
	system("pause");
	return 0;
}

  

posted @ 2012-05-24 09:51  imFolish  阅读(209)  评论(0编辑  收藏  举报