8

TEMPLATES: CODE SHARING (GENERICITY)

8.1 INTRODUCTION TO CODE SHARING

There are many programming situations where same set of operations is applied on different data types. For example, the following function exchanges the contents of two variables of type int.

image

Now, consider a situation where we also need to exchange the contents of variable of type: float and char. Accordingly, we will have to define the following two functions:

Function for float type variables:

image

Function for char type variables:

It may be noted that 99% of the code in the ...

Get Object-Oriented Programming with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.