输出结果:
Result of Int:5
Result of Double:5.2
非类型形参
template<class T,int maxSize>
class TmpStack
{
public:
TmpStack();
void push(T const &);//入栈
void pop();//出栈
T top() const;
bool isEmpty()const //返回是否为空
{
return numOfElems == 0;
}
bool isFull()const //返回是否满
{
return numOfElems == maxSize;
}
private:
T elems[maxSize];//包含元素的数组
int numOfElems;//当前元素数量
};
template<class T, int maxSize>
TmpStack<T, maxSize>::TmpStack() :numOfElems(0)
{
}
template<class T, int maxSize>
void TmpStack<T, maxSize>::push(T const &element)
{
if (numOfElems == maxSize)
throw out_of_range("TmpStack<>::push:Stack if full!");
elems[numOfElems] = element;
++numOfElems;
}
template<class T, int maxSize>
void TmpStack<T, maxSize>::pop()
{
if (numOfElems == 0)
throw out_of_range("TmpStack<>::pop:Stack if empty!");
--numOfElems;
}
template<class T, int maxSize>
T TmpStack<T, maxSize>::top() const
{
if (numOfElems == 0)
throw out_of_range("TmpStack<>::top:Stack if empty!");
return elems[numOfElems-1];
}
int _tmain(int argc, _TCHAR* argv[])
{
TmpStack<int, 20> intStackInstance;
intStackInstance.push(7);
std::cout << intStackInstance.top() << std::endl;
intStackInstance.pop();
TmpStack<string, 15> stringStackInstance;
stringStackInstance.push("string1");
std::cout << stringStackInstance.top() << std::endl;
return 0;
}
输出结果:
7
string1
比较大小
template<typename Type>
Type getMax(const Type a, const Type b)
{
return a>b? a:b;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << getMax(2.3, 3.4) << endl;
cout << getMax(2, 3) << endl;
return 0;
}
带多个模板类型形参
template<class T1,class T2,class T3>
class MySumClass
{
public:
MySumClass(){};
~MySumClass(){};
double sumTotal(T1 a, T2 b, T3 c);
private:
};
template<class T1, class T2, class T3>
double MySumClass<T1, T2, T3>::sumTotal(T1 a, T2 b, T3 c)
{
return a + b + c;
}
int _tmain(int argc, _TCHAR* argv[])
{
MySumClass<int, short, double> mySumClassInstance;
cout << mySumClassInstance.sumTotal(2, 3, 4.5) << endl;
return 0;
}
输出结果:
9.5