Motivation for using templates
So far, when we have defined a function or a class, we have had to provide input, output, and intermediate parameters. For example, let’s say we have a function to perform the addition of two int
-type integers. How do we extend this so that it handles all the other basic data types, such as float
, double
, char
, and so on? One way is to use function overloading by manually copying, pasting, and slightly modifying each function. Another way is to define a macro to do the addition operation. Both approaches have their side effects.
Moreover, what happens if we fix a bug or add a new feature for one type, and this update needs to be done for all the other overloading functions and classes later? Instead of using this silly copy-paste-and-replacement method, do we have a better way of handling this kind of situation?
In fact, this is a generic problem that any computer language can face. Pioneered by the general-purpose functional programming...