繁体   English   中英

指向成员函数的函数

[英]Pointer to function to member function

我想使用一个库(nlopt),它有一个函数set_min_objective,它接受一个指向数值函数myfunc的指针并找到它的最小值。 我想创建一个包含适当初始化成员函数的类。 然后set_min_objective将在特定实例中找到最佳值(下例中的myP)。 呼叫顺序是:

opt.set_min_objective(myfunc, NULL);

我想使用类似的东西:

opt.set_min_objective(myP.f, NULL);

编译时得到的错误是:

main.cpp: In function 'int main()':
main.cpp:79:34: error: no matching function for call to 'nlopt::opt::set_min_objective(<unresolved overloaded function type>, NULL)'
../lib/nlopt.hpp:335:10: note: candidates are: void nlopt::opt::set_min_objective(double (*)(unsigned int, const double*, double*, void*), void*)
../lib/nlopt.hpp:342:10: note:                 void nlopt::opt::set_min_objective(double (*)(const std::vector<double>&, std::vector<double>&, void*), void*)
../lib/nlopt.hpp:368:10: note:                 void nlopt::opt::set_min_objective(double (*)(unsigned int, const double*, double*, void*), void*, void* (*)(void*), void* (*)(void*))

set_min_objective接受myP.f作为函数的普通指针最简单的解决方案是什么? 请注意,myP.f和myfunc具有相同的参数和返回值类型。

谢谢,

JD

你不能直接这样做。 您正在尝试将指向成员函数的指针作为指向函数的指针传递。 要做的就是编写一个包装函数(一个普通函数),例如,将计算委托给对象的成员函数,例如,一个全局对象。

编辑

实际上,你很幸运: opt.set_min_objective的第二个参数是一个指向你的数据的指针,它将传递给你传递指针作为第一个参数的函数。 这意味着您的包装函数不必使用全局对象。

class YourClass
{
public:
    double f(unsigned int i, const double*, double*, void*);
};

double wrapper(unsigned int i, const double* a, double* b, void* o) {
    // not sure what you'd need the last param for, but you say you have it...
    reinterpet_cast<YourClass*>(o)->f(i, a, b, o);
}

然后:

YourClass myP;
opt.set_min_objective(wrapper, &myP);

另一个编辑。 其他人遇到类似的问题: http//www.cplusplus.com/forum/general/73166/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM