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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access