Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here:
Syntax
template <class type> class class-name { . . . }
Example
#include <iostream> using namespace std; // template class declaration template<class T> class MyClass { T x, y; public: MyClass(T a, T b) // constructor to initialize x,y with values { x = a; y = b; } T sum() // return of type T { return x + y; // returning sum } }; int main() { MyClass<int> forInteger(10, 3); cout << "integer sum: " << forInteger.sum() << "\n"; MyClass<double> forDouble(10.6, 3.9); cout << "integer sum: " << forDouble.sum() << "\n"; return 0; }
Output
integer sum: 13 integer sum: 14.5