调用C++成员函数指针,而不知道哪个类



我正在尝试调用一个成员函数,可能给定对象指针,而不知道成员函数来自哪个类。这可能吗?

基本上,我希望像下面这样的东西起作用。

class Foo{
public:
Foo(void* object): obj(object) {}
void callFunc(void (*func)()){
obj->*func();
}
private:
void* obj;
};
class Bar{
public:
Bar(): foo(this) {}
void callSomeFunc(){
callFunc(someFunc);
}
void someFunc(){
cout << "hin";
}
private:
Foo foo;
};
int main(){
Bar bar;
bar.callSomeFunc();
return 0;
}

它看起来很像一个XY问题。无论如何,让我们尝试按原样回答您的问题。

函数成员绑定到它所属的类的类型,除非它是静态的(后者被视为普通函数指针,您甚至不必将指针传递给实例即可调用它(。
因此,您可以callFunc函数模板,让它为您推断类型:

template<typename T>
void callFunc(void (T::*func)()){
(static_cast<T*>(obj)->*func)();
}

看到它在魔杖盒上启动并运行。

请注意,如果obj的原始类型(您擦除以将其放入void *的类型(不是T,则在static_cast时可能会出错。


以下是您可以在上面的链接中看到的完整代码:

#include<iostream>
class Foo{
public:
Foo(void* object): obj(object) {}
template<typename T>
void callFunc(void (T::*func)()){
(static_cast<T*>(obj)->*func)();
}
private:
void* obj;
};
class Bar{
public:
Bar(): foo(this) {}
void callSomeFunc(){
foo.callFunc(&Bar::someFunc);
}
void someFunc(){
std::cout << "hin";
}
private:
Foo foo;
};
int main(){
Bar bar;
bar.callSomeFunc();
return 0;
}

这是一个XY问题。使用std::function和/或λ。

#include <functional>
#include <iostream>
class Foo{
public:
template<class F>
void callFunc(F&& f){
f();
}
};
class Bar : public Foo{
public:
Bar(): foo() {}
void callSomeFunc(){
this->callFunc([this]{ someFunc(); });
}
void someFunc(){
std::cout << "hin";
}
private:
Foo foo;
};
int main(){
Bar bar;
bar.callSomeFunc();
return 0;
}

虽然我发现@skypjack提供的解决方案更优雅,但这里有一个将Foo类(而不是"仅"函数(作为一个整体模板的解决方案。因此,obj的类型在整个Foo类中都是已知的,这可能是一个优势(也可能不是(。

此外,另请参阅将成员与关联对象一起存储的解决方案。也许它在某种程度上有所帮助:

#include <functional>
#include <iostream>

template<class T>
class Foo {
public:
Foo(T& obj) : _obj(obj) {}
void callFuncOnObj(void (T::*func)(void)) {
auto fn = mem_fn(func);
fn(_obj);
}
private:
T &_obj;
};
class Bar{
public:
Bar() : d(*this) {}
void callSomeFunc(){
d.callFuncOnObj(&Bar::someFunc);
}
void someFunc(){
cout << "hi Bar1n";
}
private:
Foo<Bar> d;
};
class Foo2 {
public:
Foo2(std::function<void(void)> f) : _f(f) {}
void callFunction() {
_f();
}
private:
std::function<void(void)> _f;
};
class Bar2{
public:
Bar2() : d(std::bind(&Bar2::someFunc,this)) {}
void callSomeFunc(){
d.callFunction();
}
void someFunc(){
cout << "hi Bar2n";
}
private:
Foo2 d;
};

int main(){
Bar bar;
bar.callSomeFunc();
Bar2 bar2;
bar2.callSomeFunc();
return 0;
}

最新更新