我必须在两个软件之间建立某种桥梁,但面临一个我不知道如何处理的问题.希望有人会有有趣的(最好)工作建议.
以下是背景:我有一个C++软件套件.我必须用另一个函数替换给定类中的某个函数,这没关系.问题是新函数调用另一个必须是静态的函数,但必须处理类的成员.这是第二个让我发疯的功能.
如果该函数不是静态的,我会收到以下错误:
error: argument of type ‘void (MyClass::)(…)’ does not match ‘void (*)(…)’
Run Code Online (Sandbox Code Playgroud)
如果我将其设置为静态,我会收到以下错误:
error: cannot call member function ‘void
MyClass::MyFunction(const double *)’ without object
Run Code Online (Sandbox Code Playgroud)
要么
error: ‘this’ is unavailable for static member functions
Run Code Online (Sandbox Code Playgroud)
取决于我是否使用"this"关键字("Function()"或"this-> Function()").
最后,类对象需要一些我无法传递给静态函数的参数(我无法修改静态函数原型),这阻止我在静态函数本身中创建一个新实例.
如何以最小的重写处理这样的情况?
编辑:好的,这是一个关于我必须做的简化示例,希望它清楚正确:
// This function is called by another class on an instance of MyClass
MyClass::BigFunction()
{
…
// Call of a function from an external piece of code,
// which prototype I cannot change
XFunction(fcn, some more args);
…
}
// This function has to be static and I cannot change its prototype,
// for it to be passed to XFunction. XFunction makes iterations on it
// changing parameters (likelihood maximization) which do not appear
// on this sample
void MyClass::fcn(some args, typeN& result)
{
// doesn't work because fcn is static
result = SomeComputation();
// doesn't work, for the same reason
result = this->SomeComputation();
// doesn't work either, because MyClass has many parameters
// which have to be set
MyClass *tmp = new MyClass();
result = tmp->SomeComputation();
}
Run Code Online (Sandbox Code Playgroud)
按照 spencercw 在最初问题下面的建议,我尝试了“您设置为指向的静态成员变量this”解决方案(全局变量在软件套件的上下文中会很棘手且危险)。
实际上我发现代码中已经实现了类似的东西(我没有写):
static void* currentObject;
Run Code Online (Sandbox Code Playgroud)
所以我只是用它,因为
((MyClass*)currentObject)->SomeComputation();
Run Code Online (Sandbox Code Playgroud)
它确实有效,谢谢!