如何向基类注册派生类成员函数指针 [英] How to register a derived class member function pointer with a base class

查看:234
本文介绍了如何向基类注册派生类成员函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与虚拟成员函数相反,我需要一个解决方案,其中在每个级别类派生中实现的函数可以注册以供基类稍后调用。 (不仅仅是最派生的实现)

As opposed to virtual member functions, I need a solution where a function implemented at each level class derivation can be registered for later call by the base class. ( Not just the most derived implementation)

为了做到这一点,我想为派生类提供一种机制来向基类注册它们的函数,类构造函数。

To do this, I was thinking on providing a mechanism for derived classes to register their function with the base class such as during the derived class constructor.

我有成员函数指针参数的麻烦。我认为Derived派生自Base,这个指针应该被自动转换。

I'm having trouble with the member function pointer argument though. I was thinking that Derived is derived from Base, the this pointer should be automatically casted.

这可以接近我想要的,或者我需要使用静态成员函数, void * static_cast

class Base
{
protected:
    typedef void (Base::*PrepFn)( int n );
    void registerPrepFn( PrepFn fn ) {};
}

class Derived : public Base
{
    Derived() {
        registerPrepFn( &Derived::derivedPrepFn );
    };

    void derivedPrepFn( int n ) {};

}

编译器错误:

error: no matching function for call to 'Derived::registerPrepFn(void (Derived::*)(int))'
note: candidates are:                 'void Base::registerPrepFn(void (Base::*)(int))'


推荐答案

如果所有你需要的是跳动的错误信息,然后强制执行:

If all you need is beating the error message, then casting will do:

class Derived : public Base
{
    Derived() {
        registerPrepFn( static_cast<PrepFn>(&Derived::derivedPrepFn) );
    };

    void derivedPrepFn( int n ) {};

}

使用 * p ,只要它实际指向一个派生):(p-> *已注册)(0)

请参阅 http://ideone.com/BB9oy 以获取实用示例。

See http://ideone.com/BB9oy for a working example.

这篇关于如何向基类注册派生类成员函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆