Similar to the function template, the specificity of the class template is also after the class template definition, with template to describe the type of the special templates, the Special class template can even define new data members and member functions, the following is a class template special example:
#include <stdio.h>
Template <class t>
Class a{
T i;
Public
A (T t) {i=t;}
T Compute () {return i*i;}
};
Template<> class a<int>{
int i;
Int J;
Public
A (int t) {i=t; printf ("specialization!\n");}
int Compute () {return i*i*i;}
void F () {}
};
int main (void) {
A<double> DA (1.1);
A<int> IA (2);
printf ("%f\n", Da.compute ());
printf ("%d\n", Ia.compute ());
return 0;
}
Operation Result:
specialization!
1.210000
8
Templates also provide function template overloading, as long as you define a function template with the same name, with different return value types and parameters, you implement the overload of the function template, and the compiler automatically selects the corresponding function template instantiation and invocation in the calling function. Examples are as follows:
#include <stdio.h>
Template <class t>
void func (T a) {
printf ("func (T) \ n");
}
Template<class T1, Class t2>
int func (T1 t1, T2 T2) {
printf ("func (t1,t2) \ n");
return 1;
}
int main (void) {
Func (1, 2);
Func (3);
return 0;
}
Operation Result:
Func (T1,T2)
Func (T)
The class template also supports inheritance mechanisms, as is the case for function templates. As with normal class inheritance, we can add new member variables and member functions to the inherited class. Examples are as follows:
#include <stdio.h>
Template<class t>
Class a{
Public
void func (T a) {
printf ("A:func (T) \ n");
}
};
Template<class T1, Class t2>
Class B:public a<t1>{
Public
void func (T1 t1, T2 T2) {
printf ("B:func (t1,t2) \ n");
}
};
int main (void) {
B<int, double> B;
B.func (1, 1.2);
A<int> a=static_cast<a<int> > (b);
A.func (2);
return 0;
}
Operation Result:
B:func (T1,T2)
A:func (T)