Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

porting isnan to c++11

Tags:

c++

c++11

When I'm switching the compiler version from gcc 4.6 to gcc 4.8 I get the following error error: call of overloaded 'isnan(double)' is ambiguous.

This is because in c++11 there are differend function declarations: C: int isnan(double) C++11: bool isnan(double)

from cpluplus:

  • In C, this is implemented as a macro that returns an int value. The type of x shall be float, double or long double.
  • In C++, it is implemented with function overloads for each floating-point type, each returning a bool value.

How can I fix this?

like image 714
Dan Lincan Avatar asked Sep 26 '13 08:09

Dan Lincan


2 Answers

Although you can mitigate this problem by not saying using namespace std; everywhere, you can avoid it by being explicit about using std::isnan:

#include <cmath>
#include <iostream>

int main()
{
  double x = ....;
  std::cout << std::boolalpha;
  std::cout << std::isnan(x) << std::endl;
}
like image 171
juanchopanza Avatar answered Oct 20 '22 14:10

juanchopanza


In C++11 there should not be ambiguity between the C and C++ isnan function. It works as expected, even with using namespace std.

Please check that you are not doing both #include <math.h> and #include <cmath>. Only include cmath.

Alternatively, perhaps you somewhere have in your project a user-defined isnan(double) function, or some header includes "math.h".

Also please note, that if one wants to write generic code, it is incorrect to use the 'std::' prefix on the math functions as it breaks the argument dependent lookup (ADL). (Because the C++ standard does not allow injecting functions in the std:: namespace)

The correct use for isnan in generic code is using std::isnan; then use just isnan on the variables. Otherwise your code with user defined floating point types such as for arbitrary precision, automatic differentiation and such wont work. The root of this inconsistency is that the built in types such as double do not reside in the namespace std but the functions that operate on them do.

like image 24
Andreas H. Avatar answered Oct 20 '22 14:10

Andreas H.