nTemplate function in C++ makes it easier to reuse classes and functions.
nA template may be viewed as a variable that can be instantiated to any data type, irrespective of whether this data type is a fundamental C++ type or a user-defined type.
The following program shows the weakness of strongly-typed languages:
int min(int a, int b) {
return a < b ? a : b;
}
double min(double a, double b) {
return a < b ? a : b;
}
The Template Solution:
template <class Type>
Type min(Type a, Type b) {
return a < b ? a : b;
}
main() {
// ok: int min(int, int);
min(10, 20);
// ok: double min(double, double);
min(10.0, 20.0);
}
No comments:
Post a Comment