C++ 中调用存储在 class 中的方法的正确语法是什么,使用不同的 class 作为方法的 'this'?

What is the correct syntax in C++ for calling a method stored inside of a class using a different class as the 'this' for the method?

我有一个这样的模板class:

class template <class T1, class T2, class CTHIS> class cachedValuesClass
{
typedef T2 (CTHIS::*ptrToInternalMethodType)(T1) const;
ptrToInternalMethodType classFuncVar;
T2 getValue(CTHIS* _this, T1 x, bool *error = NULL) const;
}

getValue 代码应该调用存储在点 this->classFuncVar 的方法,使用 _this 参数作为此调用的 "this"。我试过这样写:

 template <class T1, class T2, class CTHIS>
 T2 cachedValuesClass<T1, T2, CTHIS>::getValue(CTHIS* _this, T1 x, bool *error /*=NULL*/) const
 {
 return *_this.*this.*classFuncVar(x);
 }

但是它不起作用,我得到这个错误:

 130|error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘((const cachedValuesClass<float, float, vocationForTheorical>*)this)->cachedValuesClass<float, float, vocationForTheorical>::classFunc (...)’, e.g. ‘(... ->* ((const cachedValuesClass<float, float, vocationForTheorical>*)this)->cachedValuesClass<float, float, vocationForTheorical>::classFunc) (...)’|
 130|error: ‘this’ cannot be used as a member pointer, since it is of type ‘const cachedValuesClass<float, float, vocationForTheorical>* const’|

我尝试了几种变体,包括括号,但我无法使它起作用。 该行的正确语法应该如何?

提前致谢!

您的 getValue 方法代码中需要多一些括号,以便在调用成员函数之前将方法指针绑定到其目标对象:

return (_this->*classFuncVar)(x);
// or more complete
return (_this->*(this->classFuncVar))(x);

另请参阅:How to call through a member function pointer?