1函数模板
函数模板定义语法
template <模板参数表>
模板参数表的内容
类型参数:class(或typename) 标识符
常量参数:类型说明符 标识符
模板参数:template <参数表> class标识符
//例:求绝对值函数的模板 #include<iostream> using namespace std; template<typename T> T abs(T x){ return x < 0 ? -x : x; } int main(){ int n = -5; double d = -5.5; cout << abs(n) << endl; cout << abs(d) << endl; return 0; }
//9-1函数模板的示例 #include<iostream> using namespace std; template<class T> void outputArray(const T *array, int count){ for(int i = 0; i < count;i++) cout << array[i] << " "; cout << endl; } int main(){ const int A_COUNT = 8, B_COUNT = 8, C_COUNT = 20; int a[A_COUNT] = {1,2,3,4,5,6,7,8}; double b[B_COUNT] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8}; char c[C_COUNT] = "Welcome!"; cout << "a array contains: " << endl; outputArray(a, A_COUNT); cout << "b array contains: " << endl; outputArray(b, B_COUNT); cout << "c array contains: " << endl; outputArray(c, C_COUNT); return 0; }
2类模板
//例9-2 类模板示例 #include<iostream> #include<cstdlib> using namespace std; struct Student{ int id; float gpa; }; template<class T> class Store{//类模板:实现对任意类型数据进行存取 private: T item; bool haveValue; public: Store(); T &getElem();//提取数据函数 void putElem(const T &x);//存入数据函数 }; template<class T> Store<T>::Store():haveValue(false){} template<class T> T &Store<T>::getElem(){ //如果试图提取未初始化的数据,则终止程序 if(!haveValue){ cout << "No item present!" << endl; exit(1); //使程序完全退出,返回到操作系统 } return item; } template<class T> void Store<T>::putElem(const T &x){ haveValue = true; item = x; } int main(){ Store<int> s1, s2; s1.putElem(3); s2.putElem(-7); cout << s1.getElem() << " " << s2.getElem() << endl; Student g = {1000,23}; Store<Student> s3; s3.putElem(g); cout << "The student id is " << s3.getElem().id << endl; Store<double> d; cout << "Retrieving object D..."; cout << d.getElem() << endl;//d未初始化 return 0; }