Function Templates


  • To perform identical operations for each type of data compactly and conveniently, use function templates.
  • You can write a single function template definition.
  • Based on the argument types provided in calls to the function, the compiler automatically instantiates separate object code functions to handle each type of call appropriately.
  • Function templates are implemented like regular functions, except they are prefixed with the keyword template. Here is a sample with a function template.
    //max function returns the maximum of the two elements 
    template <class T>
    T max(T a, T b)
    {
    return a> b ? a : b;
    }
    
  • Using function templates is very easy: just use them like regular functions.
  • When the compiler sees an instantiation of the function template, for example: the call max(10, 15) in function main, the compiler generates a function max(int, int). Similarly the compiler generates definitions for max(char, char) and max(float, float) in this case.

  • Click here for example

    Program Output

    max(10, 15)= 15
    max('k', 's') = s
    Max(10.1,15.2) = 15.2
     

    Class Templates to a stack<< Previous
    Next >> Parameter values for templates

    Our aim is to provide information to the knowledge seekers. 


    comments powered by Disqus


    Footer1