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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.