Generic programming is a style of programming that helps you develop reusable code or generic algorithms that can be applied to a wide variety of data types. Whenever a generic algorithm is invoked, the data types will be supplied as parameters with a special syntax.
Let's say we would like to write a sort()
function, which takes an array of inputs that needs to be sorted in an ascending order. Secondly, we need the sort()
function to sort int
, double
, char
, and string
data types. There are a couple of ways this can be solved:
- We could write four different
sort()
functions for each data type - We could also write a single macro function
Well, both approaches have their own merits and demerits. The advantage of the first approach is that, since there are dedicated functions for the int
, double
, char
, and string
data types, the compiler will be able to perform type checking if an incorrect data type is supplied. The disadvantage of the first approach is that we have to write...