15.2 FUNCTION TEMPLATE

Function templates enable us to construct a family of related functions. Suppose we want to have function add(), which adds two numbers, C++ is strongly typed. Hence, if we define add( int , int), it will not work properly for floats or complex numbers. Here the concept of template can be brought in. We will declare function add to have parameters of type ‘T’, where ‘T’ is template type, e.g.,

template < class T>

void add( T a, T b , T& c);

First line tells the compiler that we are using a generic type ‘T’. Please note that word class is used as a generalization for type. Once T is accepted as some type, declaration of the function is logical. While defining the function, syntax of C++ requires addition of “template <class ...

Get Object Oriented Programming with C++, Second Edition 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.