Example of Overloading a Template Function

In the case of the approximate() function 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);
      };

if the two input values are of different types, overloading resolution does not take place:

      float a=3.24;
      double b=3.35;
      if (approximate(a,b))  // error, different types
      { /* ... */ }

The solution is to force a conversion to one of the available function types by explicitly declaring the function for the chosen type. To resolve the float/double example, include the following function declaration:

      int approximate(double a, double b);
      // force conversion of the float to double

This declaration creates a function approximate() that expects two arguments of type double, so that when approximate(a,b) is called , the overloading is resolved by converting variable a to type double.