C++中的程式碼重用(六)
阿新 • • 發佈:2019-01-07
成員模板
//example.h #ifndef _EXAMPLE_H_ #define _EXAMPLE_H_ /*模板類和模板函式一樣也存在隱、顯式例項化以及顯式例項化,部分具體化*/ /*模板成員*/ #include<iostream> template<typename T> class Example { private: template<typename V> class child { private: V data; public: child(){}; child(V d) :data(d){} V & getd(){ return data; } void show()const{ cout << "Child data=" << data << endl; } }; child<T>temp1; child<int>temp2; public: Example(){} Example(T d, int i) :temp1(d), temp2(i){} template<typename U> U func(U u, T t){ return ((temp2.getd() + temp1.getd()))*u / t; } void show(){ temp1.show(); temp2.show(); } }; #endif //_EXAMPLE_H_ //main.cpp /** *Copyright U+00A9 2018 XXXXX. All Right Reserved. *Filename: *Author:XXXX *Date:2018.12.15 *Version:VS 2013 *Description: **/ #include<iostream> //#include<cstdlib> #include"windows.h" #include"example.h" using namespace std; int main() { Example<double>test(3.5, 2); cout << "test.show():\n"; test.show(); cout << "test.func(3.5, 2.3)=" << test.func(3.5, 2.3) << endl; system("pause"); return 0; }
對於成員模板也可以寫成以下形式:
#ifndef _EXAMPLE_H_ #define _EXAMPLE_H_ /*模板類和模板函式一樣也存在隱、顯式例項化以及顯式例項化,部分具體化*/ /*模板成員*/ #include<iostream> using namespace std; template<typename T> class Example { private: template<typename V> class child; child<T>temp1; child<int>temp2; public: Example(){} Example(T d, int i) :temp1(d), temp2(i){} template<typename U> U func(U u, T t); void show(){ temp1.show(); temp2.show(); } }; template<typename T> template<typename V> class Example<T>::child { private: V data; public: child(){}; child(V d) :data(d){} V & getd(){ return data; } void show()const{ cout << "Child data=" << data << endl; } }; template<typename T> template<typename U> U Example<T>::func(U u, T t) { return ((temp2.getd() + temp1.getd()))*u / t; } #endif //_EXAMPLE_H_