• Main Menu
  • Function Templates


    Like class templates, we can also define function templates that could be used to create a family of functions with different argument types. The general format of a function template is as follows:

    template <class T> 
    return-type function-name( argument of type T ) 
    { 
        // body of function with Type T 
    } 
    

    The function template syntax is similar to that of the class template except that we are defining functions instead of classes. We must use the template parameter T as and when necessary in the function body and in its argument list.

    The following example declares a swap() function template that will swap two values of a given type of data.

    template <class T> 
    void swap(T &x, T &y ) 
    { 
        T temp = x ; 
        x = y ; 
        y = temp ; 
    } 
    

    This essentially declares a set of overloaded functions, one for each type of data. We can invoke the swap() function like any ordinary function.

    Example:

    #include<iostream.h> 
    template<class T> 
    
    void swap( T &x, T &y ) 
    { 
        T temp = x; 
        x = y; 
        y = temp; 
    } 
    
    void fun(int m, int n, float a, float b) 
    { 
        cout<<"n m and n before swap : "<<m<<" " <<n; 
        swap(m, n); 
        cout<<"n m and n after swap : "<<m<<" " <<n; 
        cout<<"n a and b before swap : "<<a<<" " <<b; 
        swap(a, b); cout<<"n a and b after swap : "<<a<<" " <<b; 
    } 
    
    void main() 
    { 
        fun(100, 200, 11.22, 33.44); 
    } 
    

    Output:

    m and n before swap :    100 200
    m and n after swap  :     200 100
    a and b before swap :    11.22 33.44
    a and b after swap  :     33.44 11.22
    

    Function Templates with Multiple Parameters

    We can use more than one generic data type in the template statement, using a comma- separated list as shown below:

    template < class T1, class T2 > 
    return-type function-name(argument of types T1, T2,…) 
    { 
        // body of the function 
    } 
    

    Example:

    //Program to illustrate the concept of using generic types in template functions
    
    #include <iostream.h>
    #include <string.h>
    template < class T1, class T2 > 
    void display(T1 x, T2 y)
    {
        cout << x << " " << y << "\n";
    }
    void main()
    {
     display(1999, "EBG");
     display(12.34, "1234");
    }
    

    Output:

    1999 EBG
    12.34 1234
    

    Got Something To Say:

    Your email address will not be published. Required fields are marked *

    C
    } 235 queries in 0.334 seconds.