How to register a function pointer of an element of a derived class with a base class

Unlike virtual member functions, I need a solution in which a function implemented in each derived class of a level can be registered for subsequent call by the base class. (Not only the most derived implementation)

To do this, I was thinking of providing a mechanism for derived classes to register their functions with the base class, for example, during the constructor of the derived class.

I'm having problems with a member function pointer argument. I thought Derived was derived from Base, the this pointer should be automatically started.

Can this be done close to what I'm trying, or do I need to use static member functions, void * and 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 ) {}; } 

Compiler Error:

 error: no matching function for call to 'Derived::registerPrepFn(void (Derived::*)(int))' note: candidates are: 'void Base::registerPrepFn(void (Base::*)(int))' 
+8
c ++ member-function-pointers
source share
2 answers

If all you need is a beating error message, then a listing is performed:

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

Name it usually with Base* p ( if it actually points to Derived ): (p->*registered)(0)

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

+12
source share

This is not allowed with oop. Behavioral switching is accomplished by polymorphizing an object class during object creation.

If you need to change the behavior of the behavior of the object after the object, you can reorganize the dynamic behavior to another set of polymorphic classes and draw a "pointer" to the class instance with the correct behavior. Please google "decorated class" software template.

0
source share

All Articles