13

所以我有这个代码:

#include "boost_bind.h"
#include <math.h>
#include <vector>
#include <algorithm>

double foo(double num, double (*func)(double)) {
  return 65.4;
}

int main(int argc, char** argv) {
  std::vector<double> vec;
  vec.push_back(5.0);
  vec.push_back(6.0);
  std::transform(vec.begin(), vec.end(), vec.begin(), boost::bind(foo, _1, log));
}

并收到此错误:

        return unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]);
.............................................................^
%CXX-E-INCOMPATIBLEPRM, argument of type "double (* __ptr64 )(double) C" is
          incompatible with parameter of type "double (* __ptr64 )(double)"
          detected during:
            instantiation of ...5 pages of boost

所以这个错误是因为'log'在 math.h 中是 extern "C"'d

我想知道如何在 foo() 中声明我的函数指针参数,以便它处理外部“C”函数。

4

2 回答 2

23

您可以尝试包含cmath,并使用static_cast<double(*)(double)>(std::log)(解决double重载所需的强制转换)。

否则,您会将功能限制为extern C功能。这会像

extern "C" typedef double (*ExtCFuncPtr)(double);

double foo(double num, ExtCFuncPtr func) {
  return 65.4;
}

另一种方法是制作foo函子

struct foo {
  typedef double result_type;
  template<typename FuncPtr>
  double operator()(double num, FuncPtr f) const {
    return 65.4;
  }
};

然后你可以传递foo()boost::bind,因为它是模板化的,它会接受任何链接。它也适用于函数对象,而不仅仅是函数指针。

于 2009-08-17T17:11:51.377 回答
4

尝试使用 typedef:

extern "C" {
  typedef double (*CDoubleFunc)(double);
}

double foo(double num, CDoubleFunc func) {
  return 65.4;
}
于 2009-08-17T17:09:22.800 回答