views:

1194

answers:

5

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)

A: 

Think you should read a little about Design Patterns, specifically the Observer Pattern.

Qt from Trolltech have implemented a nice solutions they call Signals and Slots.

epatel
A: 

Use the Observer pattern

code project example

wiki page

slf
A: 

As far as I am aware you can't do it with default variables, however if you wrote a class that took a callback function you could let other classes register that they want to be notified of any changes.

Denice
+7  A: 

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.

Adam Wright
Great explanation! I've used boost in past projects and have always been happy with the results.
Scott Saad
+1  A: 

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.

Doug T.