Example of a Function Template

If you want to create a function approximate(), which determines whether two values are within 5% of each other, you can define the following template:

      #include <math.h>
      template <class T> int approximate (T first, T second)
      {
            double aptemp=double(first)/double(second);
            return int(abs(aptemp-1.0) <= .05);
      };

Assuming you have two values of type float you want to compare, you can use the approximate function template:

      float a=3.24, b=3.35;
      if (approximate(a,b))
            cout << "a and b are pretty close" << endl;

A template function int approximate(float,float) is generated to resolve the call.