Implementation of C++ function template

  • 2020-06-12 10:07:49
  • OfStack

If a program's function is to process a particular data type, and the data type being processed is described as a parameter, then the program can be rewritten as a template, which allows the program to process any other data type in the same way.

This section is mainly about the function template of C++. The general form of function template definition 1 is:


template < Type form parameter table >  The return type    The function name ( parameter )
{
  // function 
}

Take a look at an example:


#include <cstdio>
#include <iostream>
using namespace std;
// A function template 
template <class T>
T max(T & a, T & b)  
{
 return a > b ? a : b;
}
int main(void)
{
 int x, y;
 x = 1;
 y = 4;
 cout << "max = " << max<int>(x, y) << endl;
 cout << "max = " << max<double>(1.234, 5.567) << endl;
 cout << "max = " << max(21.234f, 51.567f) << endl;
 return 0;
}

Operation results:

[

max = 1
max = 5.567
max = 51.567

]

conclusion


Related articles: