A generic class : generic class « template « C++ Tutorial






#include <iostream> 
using namespace std; 
 
template <class T> class MyClass { 
  T x, y; 
public: 
  MyClass(T a, T b) {  
    x = a; 
    y = b; 
  } 
  T div() { return x/y; } 
}; 
 
int main() 
{ 
  
  MyClass<double> d_ob(10.0, 3.0 );  // doubles. 
  cout << "double division: " << d_ob.div() << "\n"; 
 
  MyClass<int> i_ob(10, 3);         // for ints. 
  cout << "integer division: " << i_ob.div() << "\n"; 
 
  return 0; 
}
double division: 3.33333
integer division: 3








13.12.generic class
13.12.1.A generic class
13.12.2.Operator overload for generic parameters
13.12.3.Class specialization
13.12.4.array template
13.12.5.Use two generic data types in a class definition