Class specialization : generic class « template « C++ Tutorial






#include <iostream> 
using namespace std; 
 
template <class T> class MyClass { 
  T x; 
public: 
  MyClass(T a) {  
    cout << "Inside generic MyClass\n"; 
    x = a; 
  } 
  T getx() { return x; } 
}; 
 
// Explicit specialization for int. 
template <> class MyClass<int> { 
  int x; 
public: 
  MyClass(int a) {  
    cout << "Inside MyClass<int> specialization\n"; 
    x = a * a; 
  } 
  int getx() { return x; } 
}; 
 
int main() 
{ 
  MyClass<double> d(10.1); 
  cout << "double: " << d.getx() << "\n\n"; 
 
  MyClass<int> i(5); 
  cout << "int: " << i.getx() << "\n"; 
 
  return 0; 
}
Inside generic MyClass
double: 10.1

Inside MyClass specialization
int: 25








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