C++语言一个重要特性,利用模板机制可以明显减少冗余信息,能大幅度的程序代码。
(A)函数模板:(instance)
1 #include<iostream> 2 using namespace std; 3 4 template<typename ElementType> 5 6 void display(ElementType array[],int numElements) 7 { 8 for(int i = 0;i < numElements;i ++) 9 { 10 cout<<array[i]<<" "; 11 } 12 cout<<endl; 13 } 14 15 int main() 16 { 17 double x[] = {1.1,2.2,3.3,4.4,5.5}; 18 display(x,5); 19 int num[] = {1,2,3,4}; 20 display(num,4); 21 return 0; 22 }
有多个类型参数的函数模板(instance)
#include<iostream> using namespace std; template <typename para1,typename para2> void two_para(para1 x,para2 y) { cout<<x<<" "<<y<<endl; } int main() { two_para(99,"ZhangHua"); two_para(123.45,888); return 0; }
函数模板的重载(instance)
#include <iostream> using namespace std; template <typename type> type min(type x,type y) { return (x < y) ? x : y; } template <typename type> type min(type x,type y,type z) { type t; t = (x < y) ? x : y; return (t < z) ? t : z; } int main() { int m = 10,n = 20,min2; double a = 10.1,b = 20.2,c = 30.3,min3; min2 = min(m,n); min3 = min(a,b,c); cout<<min2<<" "<<min3<<endl; return 0; }
当然函数模板也可以和非函数模板进行重载,这里不给出instance了。
(B)接下来我们讨论一下类模板问题:
instance:
#include <iostream> using namespace std; template <typename Type > class Three { public: Three(Type a,Type b,Type c) { x = a; y = b; z = c; } Type sum() { return x + y + z; } private: Type x,y,z; }; int main() { Three <int> sum1(3,5,7); Three <double> sum2(12.34,34.56,56.78); cout<<sum1.sum() <<" "<<sum2.sum()<<endl; return 0; }
instance2:
#include <iostream> using namespace std; template <typename T> class Three { public: Three(T a,T b,T c); T sum(); private: T x,y,z; }; template <typename T> Three<T>::Three(T a,T b,T c) { x = a; y = b; z = c; } template <typename T> T Three<T>::sum() { return x + y + z; } int main() { Three <int> sum1(3,5,7); Three <double> sum2(12.34,34.56,56.78); cout<<sum1.sum()<<" "<<sum2.sum()<<endl; return 0; }
(C)要注意的问题:
1.template语句与函数模板定义语句之间不能插入其他语句。instance
template <typename T>
int i;//注意这里不能插入任何其他语句
class Three
{
public:
Three(T a,T b,T c);
T sum();
private:
T x,y,z;
};
2.函数模板与同名非模板函数可以重载,这时调用顺序问题:首先寻找一个参数完全匹配的非模板,如果找到则调用它,若没有找到,则寻找函数模板,将其实例化。
恰当运用可以很好的处理一般与特殊的关系。还是补充个instance吧:
#include <iostream> using namespace std; template <typename T> T min(T x,T y) { cout<<"调用模板函数:"; return (x < y) ? x : y; } int min(int x,int y) { cout<<"调用非模板函数:"; return (x < y) ? x : y; } int main() { int elem1 = 10,elem2 = 56; double d1 = 50.1,d2 = 5435.23; char ch1 = 'k',ch2 = 'n'; cout<<min(elem1,elem2)<<endl; cout<<min(d1,d2)<<endl; cout<<min(ch1,ch2)<<endl; return 0; }
3.类模板在使用时必须在类模板名字后面加上<类型参数>:
Three <int> sum1;