在模板函数中使用 isnan

Using isnan in template function

我有以下代码:

  template<int FORMAT>
  int double_to_bulk(double value,
                       char* buf,
                       double max_num,
                       int* state = NULL)
  {
     if (isnan(value))
     {
        //Something to do
        return 1;
     }
     //Something more to do
  }

还有奇怪的编译错误:

myfile.h: In function ‘int double_to_bulk(double, char*, double, int*)’:

myfile.h:351: error: there are no arguments to ‘isnan’ that depend on a template parameter, so a declaration of ‘isnan’ must be available

myfile.h:351: error: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)

但是我真的不想用-fpermissive

我用的是gcc 4.1.2,比较旧,不过没关系。为什么在模板函数中使用isnan会出现问题?

您似乎没有 isnan 的可用定义。您是否在源代码中包含了定义 isnan 的适当头文件?这里似乎没有任何内容取决于您的模板参数。

添加行 #include<cmath> 应该可以解决问题。

如果任何参数确实依赖于模板参数(例如,如果其中一个参数具有模板参数类型),编译器将仅在您实例化模板时检查 isnan 是否存在,这将无论如何都可能会导致错误,只是稍后,或者如果您从不使用该模板,则可能根本不会。

不要使用 -fpermisive,它可能只会将错误延迟到 link 时间