Re: Casting function parameter from Base* to Derived*
Andrey Tarasevich wrote:
Imagine code like this:
void DerivedHandler(Derived*);
Handlers[&typeid(Derived)] =
reinterpret_cast<Handler*>(&DerivedHandler);
Base* P = ...;
std::map<const std::type_info*, Handler*>const_iterator It =
Handlers.find(&typeid(*P));
if (It != Handlers.end()) (*(It->second))(P);
Is it safe?
No. In order to "fix" the code you'd have to complete the "round trip"
conversion by adding an extra cast:
std::map<const std::type_info*, Handler*>const_iterator It =
Handlers.find(&typeid(*P));
if (It != Handlers.end())
reinterpret_cast<void (*)(Derived*)>(t->second)(P);
But the need for a hardcoded cast essentially defeats the purpose of the code,
as I understand it. What you are trying to use is not a viable approach to
run-time type-based dispatch, as long as you care about the safety of the code.
Without knowing more details about what you are trying to implement it is hard
to understand why you even need such a dispatcher and, therefore, hard to
suggest an alternative technique. Can you provide more details?
I have a layered application archirecture. Some layer is generating
event and pass it to the next and so on. I want to separate layers form
each other giving simply one door between them:
void HandleEvent(Event&);
Stright way is to create personal door for each event
class IEventHandler
{
void HandleEvent(Event1&);
void HandleEvent(Event2&);
void HandleEvent(Event3&);
....
}
But:
1. such interface will grow when adding new event types
2. each HandleEvent() will contain the same code to dispatch events by
another (not event type) characteristics - in real code I have std::map
not with typeid(Event) key, but with a tuple of event characterictics
(with typeid(Event) as not even first member).
Currently I have simple handlers registration like this:
void SomeHandler(SomeEvent&)
{
// handle event of type SomeEvent
// form MODULE_A initiated by SUBSYSTEM_X
}
int main()
{
Handlers.Register<SomeEvent>(MODULE_A, SUBSYSTEM_X, SomeHandler);
...
}