template for a simple test
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// the function template to searching the minimum value from an array of different type
template <class ElemType>
ElemType calcmin(ElemType elemField[], int iFieldSize)
{
int iMin = 0;
for (int i=0; i < iFieldSize; i++)
{
if (elemField[i] < elemField[iMin])
{
iMin = i;
}
}
return elemField[iMin];
}
// for test
void LetsTestFunctionTemplate()
{
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);
int iSize2 = sizeof(dField) / sizeof(double);
double d = calcmin(dField, iSize2);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Defining a class template is almost similar to defining a function template. Let's catch up the example I used at the beginning,
// the common stack class to handle different data type's stack. The prototype will be defined as the following:
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)
{
}
template<class ElemType, int iSize>
Stack<ElemType, iSize>::~Stack()
{
}
template<class ElemType, int iSize>
void Stack<ElemType, iSize>::push(const ElemType& anElement)
{
bErrorOccd = (iTop == iSize);
if (!bErrorOccd)
{
elems[iTop++] = anElement;
}
}
template<class ElemType, int iSize>
void Stack<ElemType, iSize>::pop(ElemType& anElement)
{
bErrorOccd = (iTop == 0);
if (!bErrorOccd)
{
anElement = elems[--iTop];
}
}
template<class ElemType, int iSize>
bool Stack<ElemType, iSize>::isEmpty()const
{
return (0 == iTop);
}

浙公网安备 33010602011771号