指向C ++类成员函数作为全局函数参数的指针? [英] Pointer to a C++ class member function as a global function's parameter?
问题描述
我在调用全局函数时遇到了问题,该函数将指向函数的指针作为参数。
这是全局函数的声明:
int lmdif ( minpack_func_mn fcn, void *p, int m, int n, double *x,
double *fvec, double ftol)
minpack_func_mn符号是用于指向函数的指针的typedef,定义为:
The "minpack_func_mn" symbol is a typedef for a pointer to a function, defined as:
typedef int (*minpack_func_mn)(void *p, int m, int n, const double *x,
double *fvec, int iflag );
我想使用指向a成员函数的指针来调用 lmdif函数我创建的类,这是该类函数的声明:
I want to call the "lmdif" function with a pointer to a function which is a member of a class I created, and here is the declaration of this class function:
int LT_Calibrator::fcn(void *p, int m, int n, const double *x,
double *fvec,int iflag)
I正在调用这样的全局函数:
I am calling a global function like this:
info=lmdif(<_Calibrator::fcn, 0, m, n, x, fvec, ftol)
不幸的是,我得到了一个编译器错误,它表示:
错误C2664:'lmdif':无法将参数1从'int(__thiscall LT_Calibrator :: *)(void *,int,int,const double *,double *,int)'转换为'minpack_func_mn'
1>那里没有可以进行这种转换的上下文。
Unfortunately, I get a compiler error, which says: "error C2664: 'lmdif' : cannot convert parameter 1 from 'int (__thiscall LT_Calibrator::* )(void *,int,int,const double *,double *,int)' to 'minpack_func_mn' 1> There is no context in which this conversion is possible"
有没有办法解决这个问题?
Is there any way to solve that problem?
推荐答案
您需要一个非成员或静态成员函数;成员函数指针不能代替您的函数类型,因为它需要实例来调用它。
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.
如果您的函数不需要访问a LT_Calibrator
实例,则可以简单地将其声明为静态,或使其具有自由功能。否则,您似乎可以使用第一个参数( void * p
)将实例指针传递到蹦床函数中,然后可以调用成员函数。与此类似:
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, ...);
这篇关于指向C ++类成员函数作为全局函数参数的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!