libstdc++/3181: Unable to use sqrt,cos,sin,... with int argument.

Peter J. Stieber pete@toyon.com
Wed Jun 20 09:20:00 GMT 2001


The book by Nicolai Josuttis "The C++ Standard Library - A Tutorial and
Reference" has a good discussion of this topic (pp.581-582 in my copy). The
fact that standard conforming behavior is defined as overloading the
functions for all floating-point types (float, double and long double) leads
to this problem. In the old days, non-standard function names were used
(sqrtf, sqrtl, cosf, cosl,...) for the other floating point types, so
implicit conversion would work. It is common in numeric programming
(although not good practice) to see code like:

double Pi = acos(-1);

This will now cause problems, but it's always nice to work with legacy code.
Since the old standard function names were defined for double
FunctionName(double), you could overload for all numeric types and cast:

namespace std
{
  double sqrt(int a)
  {
    return sqrt(static_cast<double>(a));
  }
  double sqrt(long a)
  {
    return sqrt(static_cast<double>(a));
  }
.
.
.
};

This behavior could be controlled by compiler switches or using the
preprocessor.

The work-around I use in my code is to make the following changes

acos(-1)  change to acos(-1.0)

or

int i;
acos(i) changes to acos(static_cast<double>(i))

but for large projects, this would be a pain.





More information about the Gcc-bugs mailing list