Template Introduction
Templates and Polymorphism
Polymorphism: The ability of a variable, function, or class to take more than one form.
We have actually seen different methods of achieving polymorphism
- ad-hoc polymorphism: function overloading
- true polymorphism: virtual member functions, dynamic binding
A third method of achieving polymorphism is through parameters, which
works at compile time.
Motivation
- Often want to accomplish similar task for different types of data
- Could overload functions for each data type
float max ( const float a, const float b );
int max ( const int a, const int b );
Rational max ( const Rational& a, const Rational& b);
myType max ( const myType& a, const myType& b);
- Code for each looks the same
if ( a < b )
return b;
else
return a;
- Algorithm itself is independent of data type
C++ has two types of parametric polymorphism:
- Function templates
- Class templates