Class Templates
Generic class which having(Generic member variables, Generic member functions)
template <class T> //OR <typename T>
class A {
//Generic Member variables
A a, b;
public:
A (T x, T y) : a(x), b(y) {}
A add ();
};
//Template statement need to be written again when template class function is defined outside template class
//
template <class T>
T A <T>::add(){
return a+b;
}
int main() {
//Compiler cannot deduce template parameter type(s) for class template.
//We need to tell compiler the data types we would be using
A <int> obj(5,6);
cout << obj.add(); //11
A <float> obj1(5.6,6.7);
cout << obj1.add();
//If arguments are of other type and template-type of other type. Compiler will ignore Argument type
A <int> obj2(5.6,6.7); //C
cout << obj2.add();
}
How Internally works?
On compile time, compiler creates seperate class for different parameter types.
/*
Test <int>::Test() //class-1
Test <double>::Test() //class-2
*/
template <class T>
class Test
{
T val;
public:
static int count;
Test() { count++; }
};
//Only 1 copy of static variable is kept per class
template <class T>
int Test <T>::count = 0;
int main() {
Test <int> a;
Test <int> b;
Test <double> c;
cout << Test <int>::count; //2
cout << Test <double>::count; //1
return 0;
}
0 templated argument
//0 templated arguments
template < int n >
struct st {
static const int val = 2 * st::val;
};
//0 templated arguments
template <>
struct st < 0 > {
static const int val = 1 ;
};
int main() {
cout << s<10>::val; //Output=1024
return 0;
}