Custom events in C++?


Question

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)

1
8
9/16/2008 10:39:37 PM

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.

10
9/16/2008 10:52:42 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon