Dan Lincan
Dan Lincan

Reputation: 1065

porting isnan to 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:

How can I fix this?

Upvotes: 12

Views: 6732

Answers (2)

Andreas H.
Andreas H.

Reputation: 6105

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.

Upvotes: 2

juanchopanza
juanchopanza

Reputation: 227498

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;
}

Upvotes: 14

Related Questions