标签:clu bsp namespace get int i++ private ascii include
1 函数模板
#include <iostream> using namespace std; template <typename T> T square(T a) { return a * a; } int main(void) { cout << square<int>(3) << endl; // 可以显式告诉编译器是什么类型,也可以让编译器推断 cout << square(3) << endl; cout << square<char>(9.3) << endl; // 结果是Q ,81的ASCII码 cout << square<int>(9.3) << endl; // 结果81 cout << square(5.5) << endl; // 30.25 编译器自己推断为double }
2 类模板
#include <iostream> using namespace std; template <typename T> T square(T a) { return a * a; } template <typename T> class win { private: T arr[10]; int size; public: win():size(0) {cout << "creater" << endl; } ~win(){}; int getSize()const{ return size; } T get(int i)const{ return arr[i];} void push(T x) { arr[size] = x; size++;} void print()const; }; template <typename T> void win<T>::print()const{ for (int i = 0; i < size; i++) { cout << arr[i] << endl; } } template <typename T> win<T> operator*(const win<T> &left, const win<T> &right) { win<T> ret; for( int i = 0 ; i < right.getSize(); i++) { ret.push(left.get(i) * right.get(i)); } return ret; } int main(void) { win<int> a; a.push(1); a.push(2); a.push(3); a.push(4); a.push(5); a.push(6); a.print(); a = square(a); a.print(); }
a = square(a);这处会先调用函数模板然后由于定义了类win的乘法,调用operator *
3. 更多的例子
#include <iostream> using namespace std; struct Student { int id; float score; }; 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, 60.6 }; Store<Student> s3; s3.putElem(g); cout << "The student‘s id is " << s3.getElem().id << endl; cout << "The student‘s score is " << s3.getElem().score << endl; Store<double> d; cout << "Retrieving object D... "; cout << d.getElem() << endl; //d未初始化,执行函数D.getElement()时导致程序终止 return 0; }
标签:clu bsp namespace get int i++ private ascii include
原文地址:https://www.cnblogs.com/goodluck14/p/13328958.html