Templates Generics 模板 范型
Generic Class using Template:
#include <iostream> using namespace std; template <typename T> class Array { private: T* ptr; int size; public: Array(T arr[], int s); void print(); }; template <typename T> Array<T>::Array(T arr[], int s) { ptr = new T[s]; size = s; for (int i = 0; i < size; i++) ptr[i] = arr[i]; } template <typename T> void Array<T>::print() { for (int i = 0; i < size; i++) cout << " " << *(ptr + i); cout << endl; } int main() { int arr[5] = { 1, 2, 3, 4, 5 }; Array<int> a(arr, 5); a.print(); return 0; }
// C++ Program to demonstrate // Use of template #include <iostream> using namespace std; // One function works for all data types. This would work // even for user defined types if operator '>' is overloaded template <typename T> T myMax(T x, T y) { return (x > y) ? x : y; } int main() { // Call myMax for int cout << myMax<int>(3, 7) << endl; // call myMax for double cout << myMax<double>(3.0, 7.0) << endl; // call myMax for char cout << myMax<char>('g', 'e') << endl; return 0; }
Templates in C++ with Examples - GeeksforGeeks https://www.geeksforgeeks.org/templates-cpp/
Generics in C++ - GeeksforGeeks https://www.geeksforgeeks.org/generics-in-c/