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 four different functions even though the logic remains the same across all the functions. If a bug is identified in the algorithm, it must be fixed separately in all four functions; hence, heavy maintenance efforts are required. If we need to support another data type, we will end up writing one more function, and this will keep growing as we need to support more data types.
The advantage of the second approach is that we could just write one macro for all the data types. However, one very discouraging disadvantage is that the compiler will not be able to perform type checking, and this approach is more prone to errors and may invite many unexpected troubles. This approach is dead against object-oriented coding principles.
C++ supports generic programming with templates, which has the following benefits:
- We just need to write one function using templates
- Templates support static polymorphism
- Templates offer all the advantages of the two aforementioned approaches, without any disadvantages
- Generic programming enables code reuse
- The resultant code is object-oriented
- The C++ compiler can perform type checking during compile time
- Easy to maintain
- Supports a wide variety of built-in and user-defined data types
However, the disadvantages are as follows:
- Not all C++ programmers feel comfortable writing template-based coding, but this is only an initial hiccup
- In certain scenarios, templates could bloat your code and increase the binary footprint, leading to performance issues