Monday, February 7, 2011

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)

  • 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.

    From epatel
  • Use the Observer pattern

    code project example

    wiki page

    From slf
  • 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.

    From Denice
  • 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.

    Scott Saad : Great explanation! I've used boost in past projects and have always been happy with the results.
  • 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.

    From Doug T.

0 comments:

Post a Comment