(I see that similar questions were previously asked on SO, but the ones I saw do not seem to affect my use case. In particular, I want to know if my compilation failure is the result of an error or the result of my attempts to is verboten.)
Background
I want to implement a delegate pattern for handling events. I think that perhaps the best approach for my needs is a map of member function pointers indexed by std :: string (which represent event types.)
I started trying to accomplish this with std::function , but ran into some problems, and then decided to try using only raw MFPs. (I'm still ready to consider std::function , and I will accept an answer that shows how to fulfill my exact needs below using this approach. But I still would like to know what is wrong with my current approach.)
I managed to get this to work with one class. However, in reality, I want the delegate map to be provided by an abstract base class, and then have a derived class registering its delegates on that map. If I did not make a mistake in the code below, this seems impossible; it looks like member function pointers cannot be polymorphic.
The compilation errors that I get look like this:
mfp5.cpp: In constructor 'Derived::Derived()': mfp5.cpp:41:21: error: cannot convert 'int (Derived::*)(const Base::EventContext&)' to 'std::map<std::basic_string<char>, int (Base::*)(const Base::EventContext&)>::mapped_type {aka int (Base::*)(const Base::EventContext&)}' in assignment _delegates["foo"] = &Derived::FooEventHandler;
Questions
- Have I made a mistake in the code below, or is it really forbidden? In a nutshell, I have std :: map
Base::* , and I want to insert several Derived::* into it. - Is there any other recommended method for this?
the code
class Base { public: struct EventContext { int data1; }; Base() {} virtual int ProcessEvent(std::string event, EventContext ctx) =0; protected: typedef int (Base::* EventHandler)(const EventContext& context); typedef std::map<std::string, EventHandler> EventDelegateMap; EventDelegateMap _delegates; };
.
class Derived: Base { public: Derived(); int ProcessEvent(std::string event, EventContext ctx); private: int FooEventHandler(const EventContext& context); int BarEventHandler(const EventContext& context); int QuxEventHandler(const EventContext& context); }; Derived::Derived() :Base() { _delegates["foo"] = &Derived::FooEventHandler;
c ++ inheritance polymorphism member-function-pointers
Ryan V. Bissell
source share