Is it possible to create custom events in C++? For example, say I have the variable X, and the variable Y. Whenever X changes, I would like to execute a function that sets Y equal to 3X. Is there a way to create such a trigger/event? (triggers are common in some databases)
This is an easy way to create custom events and raise them. You create a delegate and an event in the class you are throwing from. Then subscribe to the event from another part of your code. You have already got a custom event argument class so you can build on that to make other event argument classes.
Why using custom events. The custom events allow you to decouple the code that you want to execute after another piece of code completes. For example, you can separate the event listeners in a separate script. In addition, you can have multiple event listeners to the same custom event.
Master C and Embedded C Programming- Learn as you go Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts. Events are used for inter-process communication.
This is basically an instance of the Observer pattern (as others have mentioned and linked). However, you can use template magic to render it a little more syntactically palettable. Consider something like...
template <typename T>
class Observable
{
T underlying;
public:
Observable<T>& operator=(const T &rhs) {
underlying = rhs;
fireObservers();
return *this;
}
operator T() { return underlying; }
void addObserver(ObsType obs) { ... }
void fireObservers() { /* Pass every event handler a const & to this instance /* }
};
Then you can write...
Observable<int> x;
x.registerObserver(...);
x = 5;
int y = x;
What method you use to write your observer callback functions are entirely up to you; I suggest http://www.boost.org's function or functional modules (you can also use simple functors). I also caution you to be careful about this type of operator overloading. Whilst it can make certain coding styles clearer, reckless use an render something like
seemsLikeAnIntToMe = 10;
a very expensive operation, that might well explode, and cause debugging nightmares for years to come.
Boost signals is another commonly used library you might come across to do Observer Pattern (aka Publish-Subscribe). Buyer beware here, I've heard its performance is terrible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With