模板类与普通类的比较
Usually when writing code it is easiest to precede from concrete to abstract; therefore, it is easier to write a class for a specific datatype and then proceed to a templated - generic - class. For that brevity is the soul of wit, this example will be brief and therefore of little practical application.
We will define the first class to act only on integers.
class calc
{
public:
int multiply(int x, int y);
int add(int x, int y);
};
int calc::multiply(int x, int y)
{
return x*y;
}
int calc::add(int x, int y)
{
return x+y;
}
We now have a perfectly harmless little class that functions perfectly well for integers; but what if we decided we wanted a generic class that would work equally well for floating point numbers? We would use a template.
template <class A_Type> class calc
{
public:
A_Type multiply(A_Type x, A_Type y);
A_Type add(A_Type x, A_Type y);
};
template <class A_Type> A_Type calc<A_Type>::multiply(A_Type x,A_Type y)
{
return x*y;
}
template <class A_Type> A_Type calc<A_Type>::add(A_Type x, A_Type y)
{
return x+y;
}
To understand the templated class, just think about replacing the identifier A_Type everywhere it appears, except as part of the template or class definition, with the keyword int. It would be the same as the above class; now when you instantiate an
object of class calc you can choose which datatype the class will handle.
calc <double> a_calc_class;
Templates are handy for making your programs more generic and allowing your code to be reused later.

浙公网安备 33010602011771号