I'd like to write a nested handler for consumption of json using rapidjson.
I've modeled my basic handler along the lines of the official simplereader example. This is fine for flat structures, but now I need to expand the parsing to nested objects as well.
The way I see it, I can either
have a central handler that keeps track of various domain objects to create and subsequent parse values into, or
I can change handler while parsing
Technically, I know how to do 1., but 2. seems like a neater solution, if possible.
Is it possible to change handlers mid-stream? Is there a best practice for doing this?
Thanks!
You can delegate the events to other handlers. This is often done by:
Applying the State Pattern internally in your custom handler. So that the handler can delegate the events to the current state object via polymorphism (a.k.a. virtual functions).
Using switch-case to do the delegation with an enum.
The first one has advantage if you need to deal with recursive structure. You can push the pointers of state objects in a stack.
Related
Imaging a simple double-dispatch event handling scheme:
It's cool. Moreover it works. However I see several issues here:
EventHandlerInterface must explicitly know all the events.
As a result of (1) handlers may have large space overhead because of subscribing for unused events.
What I want this structure to be, looks more like this:
As you can see, I want separate event types produced by different modules and I want for each module to implement only necessary event handling interfaces. I am not sure how to tie this all together. Ideally I would like to have a list of EventServices ready to accept any event.
One thing, I can think of here, is to have an inherited EventService for each EventHandlerInterface type and downcast event handlers to the certain type inside notify method. However it is not type safe and looks like an ugly idea.
Second approach, I can see, is to make EventService a template and statically check template argument to be a child of EventHandlerInterface. That would be type safe and will almost do what I want. However this way I can not store all EventServices into one list/vector as I would like to. Therefore this approach is not preferable.
Actually it feels like I am looking the wrong way but how to find the right one I don't know.
Thanks!
I am not sure the visitor pattern is the right approach for this problem. Sure it gives you a mechanism to achieve double dispatch but that's about it, and as you said it has drawbacks, e.g. the visitor (EventHandlerInterface) has to provide an overload for every different type of host (EventInterface). This creates a tight coupling and only makes sense if you add classes to the host hierarchy very infrequently.
Why not go for a solution according to the publish-subscribe pattern? It allows loose coupling and avoids the need of redundant interfaces. In brief, the publisher offers some events, to which subscribers can subscribe. When an event is triggerd, subscribers are notified and handle it. Subscribers only subscribe to events they find relevant. Different subscribers can provide different handling for the same type of event, which seems to be the purpose of double dispatch in your case.
In many languages (e.g. C#) there is special syntax for supporting this pattern easily. In C++ you need to use a library such as boost signals although there are others too. See also here for an example.
Working on a cpp project, where I need something like runtime event handler. My primary goal is to keep a track of various events that takes place in a sample program and based on the events specific handlers are triggered.
These event triggering handlers/functions are not contributing anything to the global objective of the sample program, but are just keeping track over various events in the cpp sample program.
My question is it prossible to create soemthing like custom eventhandlers in cpp?
If yes, is there any tutorial for creating such custom eventhandler?
eg:
Event are like failed to enter while loop. successfully entered while loop, created object, deleted object, changed global variable etc.
The simplest form of event handler is a registered callback function pointer:
enum Events {
FailedEnteringWhileLoop ,
SuccessfullyEnteredWhileLoop ,
};
typedef void(EventHandler*)(Events);
void MyEventHandler(Events ev) {
switch(ev) {
case FailedEnteringWhileLoop:
// Do something
break;
case SuccessfullyEnteredWhileLoop:
// Do something
break;
}
}
EventHandler evh = MyEventHandler;
bool whileLoopEntered = false;
while(condition) {
if(!whileLoopEntered) {
whileLoopEntered = true;
(*evh)(SuccessfullyEnteredWhileLoop);
}
}
if(!whileLoopEntered) {
(*evh)(FailedEnteringWhileLoop);
}
I am looking for events like failed to enter while loop. successfully
entered while loop, created object, deleted object, changed global
variable etc.
The C++ language itself does not track these kinds of things as "events". Generally speaking it doesn't provide hooks into any of the various fundamental activities that happen across code.
So to do what you're asking for requires building an infrastructure yourself and working it into your code in various ways. (Or finding someone else who has done the same sort of work already and made it available. Although you still would have to integrate it into your code.)
To give some idea of what might have to be done:
For creating and deleting objects you can override the new and delete operators. But that doesn't cover stack/local/etc objects. Otherwise you could wedge something the constructors and destructors of every class you want to track, or even have all of them derive from a common base class which encapsulates the tracking.
For changes to a variable, you would have to wrap that variable in a container which only exposes the ability to change it through member functions. Then those could be coded to raise events.
For entering loops... You're out of luck because a loop isn't an entity that can be extended or hooked. You literally have to put some kind of call at every loop you want to track.
As for the rest of the infrastructure, you would probably end up doing something like having all of those various "events" call to some kind of global logging object. If you need different things catch different events over the course of a program, then you might also need to build a way of registering and de-registering listeners (the listeners themselves being based on an interface to derive from or std::function or whatever suits your use case).
But in the end since there isn't an out-of-the-box way provided by the language, you might want to re-consider what you really want and what you hope to achieve with it. In fact you might be better off asking your question in terms how to accomplish the end goal you wanted this for rather than how to do this "event" system.
Using C++ & MFC I've created a class which makes it easier to add drag/drop functionality to a CWnd object. There is nothing special about it really. Currently it is used like so:
Create CDropListener object
Call a method on the CDropListener object saying which file extension you want it to react to and a function pointer of what to call when a file is dropped
Register this with the CWnd object
Delete the CDropListener object when the window is destroyed
Repeat all of the above steps if you want different file extensions for a different CWnd
It is a bit cumbersome having to create a class member variable for each listener, and I was just wondering which design pattern would be more suitable for this. I only need the member objects so that I can delete them at the end. I thought I could just use an array to store them in and it would simplify it a bit, but I also thought there might be a better way where you can just call a static function similar to DropListener::RegisterListener(CWnd* wnd, CString& extension, void(*callback) callback) and it handles all of the creating / registering / deleting for you.
I'm not familiar with MFC but from an OO point of view your design can be improved.
First identify what aspects of your requirements are most likely to change and then identify what the interfaces needed to isolate those changes are:
Changes:
The thing you want to listen for (the event)
The action you want to take (the callback)
Interfaces:
The mechanism of adding a callback related to an event to the event notifier
The mechanism of calling the callback from the notifier
So you need an Event interface, a Callback interface, and a Notifier interface.
In C++ there is a handy thing called std::function<T> where T is any callable type (a pointer to a function, a functor, a lambda). So you should probably use that for encapsulating your callbacks to give your user more freedom.
Then how may event types do you want to support? This will tell you whether you need to support different Event objects as well as how your registration will look:
// For example if you support just `Drop` events:
void addDropListener(std::function<T> callback);
// If you support many events:
void addListener(Event::Type evType, std::function<T> callback);
Once you have answered that you need to decide what a "callback" looks like (T in the above examples). This could return a value (if you want success verification) or throw a particular exception type (make sure to document the contract). Then ask if you want a copy of the event that was fired (usually you would). Assuming you are happy to only be notified of errors via exceptions then you can typedef the expected std::function like this:
typedef std::function<void (const Event&)> EventCallback;
I recommend then that your Notifier implementer use a std::vector<EventCallback> or std::map<Event::Type, std:vector<EventCallback>. The first one is useful if you want to only support one event type or to call all listeners for all events. The second is handy when you want to only notify listeners of certain types of event.
In any case if you are finding that you need to change your class code to accommodate minor changes to behaviour then you need some refactoring.
Hope that helped. :)
Need some help in sorting out design options for simulation framework in C++ (no C++11).
The user creates an "event dispatcher" and registers interest (using "watchers") in occurrence of "events". The dispatcher internally holds "event sources" which are used to detect event activation and manage notifications to watchers. There's a 1:1:1 mapping between watcher, event and event source classes.
I'd like to extend the system with
ability to register any sub-set of event watchers only in dispatcher (request unsupported notification will fail)
alternative implementations for event sources (e.g., one or multiple watchers per event)
extended event types (i.e., inheritance). Watcher and Source can handle sub-classes as if they're the base type, albeit with reduced functionality.
user defined event, event source and event watcher. For completely new events
I've considered using "event type identifiers" (either strings or Base.Derived notation), it works but doesn't feel correct (e.g., type safety relies on runtime integers, inheritance is limited, too many type casts...)
Would appreciate suggestions for code structure and mechanisms.
This is exactly the right situation to use dynamic_cast. It's only needed in one place.
All events inherit from a single base class, and all event handlers inherit from a (different) single base class. This makes all event sources and dispatchers uniform. Events are checked and filtered by the handlers in the base class.
This is a rough 10-minute sketch of what the overall structure could look like. There are no event sources in the sketch since it's not entirely clear to me what they should look like. I just fire events from main().
I have a thread that calls various APIs of a COM interface. Now I want to invoke these functions from another thread. Can you please advise how I can achieve this?
How can I implement the communication between these two threads? If I define a Message queue sort of data structure which is common for these two threads then how do I define a common data structure as the parameters are different for each COM API.
Thanks in advance
The typical way is to use callbacks. You pass your data round via pointer. You can either use polymorphism to override the method that the base class calls when you pop it off the queue. Base calls function x, you override function x in derivative classes to achieve what you want.
Another way is to use plain old callbacks. You pass the address of your function onto a queue along with any data you need, wrapped up cleanly in a struct. All of the callbacks must have the same signature, so you'll probably need to cast your data to void.
You don't define one common data structure. There is a different data structure for each different function signature. Only common thing between those structures is identifier of the function. In your thread you'll have giant switch (or std::map) that would translate function identifier to function itself. After that you know how to interpret the rest of the structure. The structures should have POD semantic.
If each thread is running as a single-threaded apartment then you can make calls on the required APIs from a remote thread by marshalling its interface pointer as an IStream from the object's owning thread to the other thread via CoMarshalInterThreadInterfaceInStream and CoGetInterfaceAndReleaseStream. Once the remote thread has an interface pointer, you can make calls on it directly.
You might also be able to do this more simply using the Global Interface Table, depending on your app's threading model. This would be the easiest way.