参考导数函数
我有一个基类和一些衍生类。我必须从它们每个人中“注册”一些静态函数。这是示例:
class Base
{
// Some interface...
};
class Der1 : Base
{
static void Do();
};
class Der2 : Base
{
static void Do();
};
void processStatic()
{
SomeFunc(Der1::Do);
SomeFunc(Der2::Do);
}
如您所见,SomeFunc
接收函数指针。我想对每个新的衍生类自动执行此操作,可能吗?也许,在Base
类中预定义静态函数并在那里注册它。但我认为这是不可能的,是吗?
也许,这会更容易理解我想要什么:
class Der1 : Base
{
Der1() { SomeFunc(Der1::Do); }
static void Do();
};
class Der2 : Base
{
Der2() { SomeFunc(Der2::Do); }
static void Do();
};
I have a base class and a few derivative. I have to 'register' some static function from each of them. Here is the example:
class Base
{
// Some interface...
};
class Der1 : Base
{
static void Do();
};
class Der2 : Base
{
static void Do();
};
void processStatic()
{
SomeFunc(Der1::Do);
SomeFunc(Der2::Do);
}
As you see, SomeFunc
receives function pointer. I want to do that automatically with each new derivative class, is it possible? Maybe, predefine static function in Base
class and register it there. But I think it's impossible, yes?
Maybe, this will be more easier to understand what do I want:
class Der1 : Base
{
Der1() { SomeFunc(Der1::Do); }
static void Do();
};
class Der2 : Base
{
Der2() { SomeFunc(Der2::Do); }
static void Do();
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑:由于明确的要求,完全替换以前的答案。
您可以使用 CRTP 声明一个专门的基类,该基类除了调用您的注册函数外什么也不做:
EDIT: Completely replacing previous answer due to clarified requirements.
You could use the CRTP to declare a specialized base class that does nothing more than call your registration function:
在 C++ 中这不是一件容易的事情,但我并不是说这是不可能的。如果您需要的只是子类名称列表,这些答案可能会有所帮助:
以某种方式在列表中注册我的类
c++ 类列表,无需初始化它们以使用静态函数
看来宏魔法或 boost mpl 是您选择的工具。
This is not an easy thing to do in C++, but I'm not saying it's impossible. If all you need is a list of subclass names, these answers might help:
Somehow register my classes in a list
c++ List of classes without initializing them for use of static functions
Seems either macro magic or boost mpl is your tool of choice.
我只是想知道,如果你做了类似的事情
I just wondering, if you did something like