adsense


Thursday, 26 November 2015

C++ LANGUAGE FUNCTION TEMPLATE

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



C++ LANGUAGE FUNCTION TEMPLATE






Function Template 


The general form of a template function definition is shown here: 


template <class type> ret-type func-name(parameter list) 

{ 
   // body of function 
}  

Here, type is a placeholder name for a data type used by the function. 
This name can be used within the function definition. 

The following is the example of a function template that returns the maximum of two values: 

#include <iostream> 
#include <string> 
 
using namespace std; 
 
template <typename T> 
inline T const& Max (T const& a, T const& b)  
{  
    return a < b ? b:a;  
}  
int main () 
34. TEMPLATES 
{ 
  
    int i = 39; 
    int j = 20; 
    cout << "Max(i, j): " << Max(i, j) << endl;  
 
    double f1 = 13.5;  
    double f2 = 20.7;  
    cout << "Max(f1, f2): " << Max(f1, f2) << endl;  
 
    string s1 = "Hello";  
    string s2 = "World";  
    cout << "Max(s1, s2): " << Max(s1, s2) << endl;  
 
   return 0; 
} 

If we compile and run above code, this would produce the following result: 

Max(i, j): 39 
Max(f1, f2): 20.7 
Max(s1, s2): World 


No comments: