一。非類型模版 ios
#include <iostream> using namespace std; template<int Size> class Index { public: int operator[](char vchar) { return vchar % Size; } }; int main() { Index<26> index; cout << index['a'] << endl; }
二。類模版函數
類模版——模版形參爲基本類型spa
#include <iostream> using namespace std; template<class Type> class trie { public: trie(Type val_1, Type val_2) : num_1(val_1), num_2(val_2) {} void print_sum() { cout << num_1 + num_2 << endl; } private: Type num_1, num_2; }; int main() { trie<int> tt(2, 5); tt.print_sum(); }
類模版——模版形參爲自定義非模版類code
#include <iostream> using namespace std; template<class Type> class trie { public: Type num; }; class Index { public: int operator[](char vchar) { return vchar % 26; } }; int main() { trie<Index> tt; cout << tt.num['a'] << endl; cout << tt.num['z'] << endl; }
類模版——模版形參爲自定義模版類blog
#include <iostream> using namespace std; template<class Type, int Size> class trie { public: Type num; }; template<int Size> class Index { public: int operator[](char vchar) { return vchar % Size; } }; int main() { trie<Index<26>, 26> t; }
類模版成員函數定義string
成員函數爲非模版函數io
#include <iostream> #include <cstring> using namespace std; template <class Type, int Size> class test { public: test(Type num) : val(num) {} void print_val(); private: Type val; }; template<class Type, int Size> void test<Type, Size>::print_val() { cout << val << " " << Size << endl; } int main() { test<int, 10> a(4); a.print_val(); }
成員函數爲模版函數class
#include <iostream> #include <cstring> using namespace std; template <class Type, int Size> class test { public: test(Type num) : val(num) {} template<class Type_fuc> void print_val(Type_fuc m); private: Type val; }; template<class Type, int Size> template<class Type_fuc> //模版類的模版函數須要另起一行 void test<Type, Size>::print_val(Type_fuc m) { cout << val << " " << Size << endl; cout << "m:" << m << endl; } int main() { test<int, 10> a(4); a.print_val("hello"); }
三。函數模版test
#include <iostream> using namespace std; template<class Type> Type sum(Type num_1, Type num_2) { return num_1 + num_2; } int main() { cout << sum(2, 3) << endl; cout << sum(2.2, 3.0) << endl; }
結果stream
5
5.2