Hi,
A template, as the name implies, is a code for a class or a function with a few parts missing. These parts are automatically filled by the preprocessor to make complete C++ code. A template helps the programmer such that writing code is minimized. For example, suppose you need to implement array classes for scalar types in your program. In classic C++ you need to write (and maintain!) one class for each data type: myArrayOfInt
, myArrayOfFloat
, myArrayOfDouble
, etc. With templates, you simply declare just once:
template <class AnyType>
class Array{
AnyType sum( AnyType a, AnyType b ){
return a + b;
}
};
The code above is ignored by the compiler. But, when you write elsewhere something like Array<int> array_of_integers;
, the preprocessor takes the template above and writes something like this on the fly for the compiler to compile:
class ArrayOfInt{
int sum( int a, int b ){
return a + b;
}
};
This is called generic programming. With templates, you improve productivity and maximize code reuse. Does this make sense?
regards,
Paulo