Sal*_*gar 10 c++ function-pointers boost-bind
所以我有这个代码:
#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));
}
Run Code Online (Sandbox Code Playgroud)
并收到此错误:
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
Run Code Online (Sandbox Code Playgroud)
所以这个错误是因为'log'在math.h中是外部的"C"
我想知道如何在foo()中声明我的函数指针参数,以便它处理extern"C"函数.
Joh*_*itb 19
你可以试着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;
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是制作foo一个仿函数
struct foo {
typedef double result_type;
template<typename FuncPtr>
double operator()(double num, FuncPtr f) const {
return 65.4;
}
};
Run Code Online (Sandbox Code Playgroud)
然后你可以传递foo()给boost::bind它,因为它是模板化的,它会接受任何联系.它也可以用于函数对象,而不仅仅是函数指针.
尝试使用 typedef:
extern "C" {
typedef double (*CDoubleFunc)(double);
}
double foo(double num, CDoubleFunc func) {
return 65.4;
}
Run Code Online (Sandbox Code Playgroud)