Templates: This feature of C++ is comparable to generics of Java. Though both of them are implemented very differently internally serve similar purpose to an extent. Templates helps in writing code at one place for multiple data types. As word indicates we specify template for a class or function to work on multiple data types. Compiler generates version for the data type using which call is made.
Example:
// Template method example
template
T sum(T a, T b) {
return a + b;
}
...
int result = sum(10, 20);
float res = sum(10.2, 20.1);
// Error: templates follow strict type checking
// float result = sum(10, 20.2);
In above example compiler will generate int and float version of the method.
Similarly we write template for the class.
Example
// Template class example
template
class Sample {
private:
T data;
public:
T getData() {
return data;
}
void setData(T d);
};
// Notice how the method is defined outside class
template
void Sample::setData(T d) {
data = d;
}
main() {
Sample sample;
sample.getData();
}
Template argument can take default values. Default values become compile time constants.
template
class Sample {
private:
T container[MAX];
};