Pointer to a C++ class member function as a global function's parameter?

余生长醉 提交于 2019-11-28 14:00:14

You need a non-member or static member function; a member function pointer can't be used in place of your function type because it requires an instance to call it on.

If your function doesn't need access to a LT_Calibrator instance, then you can simply declare it static, or make it free function. Otherwise, it looks like you can use the first argument (void *p) to pass an instance pointer into a "trampoline" function, which can then call a member function. Something along the lines of this:

// member function
int LT_Calibrator::fcn(int m, ...);

// static (or non-member) trampoline
static int fcn_trampoline(void *p, int m, ...)
{
    return static_cast<LT_Calibrator*>(p)->fcn(m,...);
}

info = lmdif(&fcn_trampoline, this, m, ...);

It looks to me like the lmdif function takes the "void *p" as a user argument that it just passes to the callback (minpack_func_mn fcn).

If that is the case, just make LT_Calibrator::fcn a static function, and pass your object as the "p" parameter. Then you can cast the user-argument (p) to get your object back, if you want.

class LT_Calibrator
{
public:
  static int fcn(void *p, int m, int n, const double *x, double *fvec,int iflag)
  {
      LT_Calibrator* pCalibrator = static_cast<LT_Calibrator*>( p );
  }
};

Then call like:

LT_Calibrator someCalibrator;

info=lmdif(&LT_Calibrator::fcn, &someCalibrator, m, n, x, fvec, ftol);
Tom

Essentially there is an implicit argument for a member function (the this pointer) which makes this tricky. Check out this FAQ entry for more information.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!