既然isnan可以是宏(在C++ 98中)或在命名空间std中定义的函数(在C++ 11中),这个简单的例子说明了编写在两种情况下都有效的代码的明显(并且可能是天真的)方式.
#include
int main() {
double x = 0;
using namespace std;
isnan(x);
}
但是,编译它会在GCC(使用-std = c ++ 11)和Clang中产生错误:
test.cc: In function ‘int main()’:
test.cc:6:10: error: call of overloaded ‘isnan(double&)’ is ambiguous
isnan(x);
^
test.cc:6:10: note: candidates are:
In file included from /usr/include/features.h:374:0,
from /usr/include/x86_64-linux-gnu/c++/4.8/bits/os_defines.h:39,
from /usr/include/x86_64-linux-gnu/c++/4.8/bits/c++config.h:426,
from /usr/include/c++/4.8/cmath:41,
from test.cc:1:
/usr/include/x86_64-linux-gnu/bits/mathcalls.h:234:1: note: int isnan(double)
__MATHDECL_1 (int,isnan,, (_Mdouble_ __value)) __attribute__ ((__const__));
^
In file included from test.cc:1:0:
/usr/include/c++/4.8/cmath:626:3: note: constexpr bool std::isnan(long double)
isnan(long double __x)
^
/usr/include/c++/4.8/cmath:622:3: note: constexpr bool std::isnan(double)
isnan(double __x)
^
/usr/include/c++/4.8/cmath:618:3: note: constexpr bool std::isnan(float)
isnan(float __x)
^
为什么在C++ 11中这是不明确的,以及如何使它适用于C++ 98和C++ 11,最好不需要太多的条件编译?