Joh*_*ang 4 c c++ templates function-pointers
我正在使用来自http://users.ics.forth.gr/~lourakis/levmar/的库,该库是用C语言编写的.
但是我将它包含在成员函数"dlevmar_der"中,该函数期望两个函数指针作为其参数:
int dlevmar_der(
void (*func)(double *p, double *hx, int m, int n, void *adata),
void (*jacf)(double *p, double *j, int m, int n, void *adata),
double *p, /* I/O: initial parameter estimates. On output contains the estimated solution */
double *x, /* I: measurement vector. NULL implies a zero vector */
int m, /* I: parameter vector dimension (i.e. #unknowns) */
int n, /* I: measurement vector dimension */
int itmax, /* I: maximum number of iterations */
double opts[4],
double info[LM_INFO_SZ],
double *work,
double *covar,
void *adata
)
Run Code Online (Sandbox Code Playgroud)
我有两个非静态成员函数CallBack和MyJac的简化模板类.(假设我在类中还有m_solution,m_info等所有其他属性):
Template<class F>
class MyClass
{
public:
typedef void (MyClass<F>::*FuncPtrType)(float*);
void Start()
{
this->Run(&MyClass<F>::MyJac);
}
protected:
void Callback(ValueType x[], ValueType result[], int m, int n, void* adata){ // some code }
void MyJac(ValueType x[], ValueType result[], int m, int n, void* adata){ // some code }
void Run(FuncPtrType func)
{
int iterCount = dlevmar_der(&MyClass<F>::Callback, func,
(double*)&this->m_solution[0],
(double*)&zero[0],
this->m_function.NumberOfParameters,
this->m_function.NumberOfFunctionValues,
this->m_maxIterations,
this->m_options,
this->m_info,
NULL,
NULL,
static_cast<void*>(this));
}
}
Run Code Online (Sandbox Code Playgroud)
但是,在调用Start()
函数时,我在"运行"函数中遇到错误,说:error C2664: 'slevmar_der' : cannot convert from 'void (__thiscall MyClass<F>::* )(float *,float *,int,int,void *)' to 'void (__cdecl *)(float *,float *,int,int,void *)
我的问题是dlevmar_der
函数是否只能将函数指针指向静态成员函数?或者有什么方法可以使用非静态成员函数dlevmar_der
实现?
你需要建立一个蹦床功能.
只是通过this
作为adata
参数和写回投下一个回调函数adata
到适当的类型化的指针,并调用方法.例如:
void myFunc(double *p, double *hx, int m, int n, void *adata) {
MyClass *self = static_cast<MyClass>(adata);
self->funcMethod(p, hx, m, n, self->func_adata);
}
Run Code Online (Sandbox Code Playgroud)