传递和投射方法指针
问题描述:
我努力创建派生类并将方法指针从它传递给基类,以便在基类中声明的函数可以调用它(通过接口调用派生类的函数)。传递和投射方法指针
目标是创建派生类来引入它们自己的资源和函数,但是通过在基类提供的函数中调用其中一个函数来调用函数应该是可能的。为此,我需要将派生的成员函数指针传递给基类。
这里是我的尝试:
class KeyFunction
{
void(*KeyFunction::KeyFuncPtr)() = nullptr; //pointer to a method of this class to store standard behavior for call
public:
KeyFunction(void(*KeyFunction::KeyFunc)()) : KeyFuncPtr(KeyFunc) {} //constructor which takes in standard behavior
void func() //standard call of the function
{
if(KeyFuncPtr)KeyFuncPtr(); //call with ensurance there's something to be called
}
void operator()() //make KeyFunction class callable
{
func();
}
};
class customRessource{
public:
string up = "UP";
string down = "DOWN";
};
class customKeyFunc : public KeyFunction
{
customRessource& r;
public:
void moveup() //possible behavior
{
cout << r.up;
}
void movedown()
{
cout << r.down;
}
customKeyFunc(void(*customKeyFunc::KeyFunc)()) :KeyFunction((void(*KeyFunction::)()) (KeyFunc)){}
};
int main()
{
customKeyFunc Up(&(customKeyFunc::moveup)); //setup functions
customKeyFunc Down(&customKeyFunc::movedown);
Up(); //call functions
Down();
getchar();
return 0;
}
末主要功能显示了应该的方式来使用类。
首先:我在每个类的构造函数中的类型都是疯狂的(我尝试了很多关于如何编写成员指针的搜索,但我仍然不太稳定) 有人可以帮助我获得它们对 ?
我可以做到这一点(尤其是像我在customKeyFunc构造函数中一样强制转换成员指针)吗?我是以正确的方式解决这个问题,还是我觉得太复杂了?
非常感谢您的帮助!
答
这样的事情?
#include <functional>
#include <string>
#include <iostream>
class customResource{
public:
const std::string up = "UP";
const std::string down = "DOWN";
};
class customKeyFunc
{
const customResource& r;
public:
customKeyFunc(const customResource& r) : r(r) {}
void moveup() //possible behavior
{
std::cout << r.up;
}
void movedown()
{
std::cout << r.down;
}
};
int main()
{
customResource r;
customKeyFunc f(r);
auto Up = std::function<void()>(std::bind(&customKeyFunc::moveup, f));
auto Down = std::function<void()>(std::bind(&customKeyFunc::movedown, f));
Up(); //call functions
Down();
return 0;
}
std::function<void()>
是一个多态函数对象,将复制任何对象:
是可移动的或可复制,并
实现
void operator()
看起来像你对我正试图重塑虚拟方法。重新创造*总是一项艰巨的工作。 –
看起来像[CRTP]的用例(https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) – Rerito
有没有你不使用虚函数的原因? – ShuberFu