Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom events in C++?

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)

like image 267
Adam Avatar asked Sep 16 '08 22:09

Adam


People also ask

What is custom event in C#?

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.

What is the purpose of custom events?

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.

What is event in C programming?

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.


2 Answers

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.

like image 96
Adam Wright Avatar answered Sep 28 '22 17:09

Adam Wright


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.

like image 27
Doug T. Avatar answered Sep 28 '22 15:09

Doug T.