Understanding the Need for Templates
Learn how the use of templates in C++ addresses specific programming challenges.
We'll cover the following...
Each language feature is designed to help with a problem or task that developers face when using that language. The purpose of templates is to help us avoid writing repetitive code that only differs slightly.
Writing a function
To exemplify this, let’s take the classical example of a max
function. Such a function takes two numerical arguments and returns the largest of the two. We can easily implement this as follows:
int max(int const a, int const b){return a > b ? a : b;}
This works pretty well, but as we can see, it will only work for values of the type int
(or those that are convertible to int
). What if we need the same function but with arguments of the type double
? Then, we can overload this function (create a function with the same name but a different number or type of ...