next up previous contents
Next: Example 3: Event recorder Up: listener Previous: Example 1: Templated events   Contents

Example 2: Using EventFilter

  class DoubleEvent: public Event {
  public:
    DoubleEvent(double d): d_(d) {}
    double d() const {return d_ ;}
  public:
    double d_ ;
  } ;

  class S: public Subscriber {
  public:
    void event(DoubleEvent* e) {std::cerr << "d = " << e->d() << std::endl ;}
  } ;

  class SFilter: public EventFilter {
  public:
    SFilter(double limit): limit_(limit) {}
    virtual bool filter(Event* e) {
      DoubleEvent* ee = dynamic_cast<DoubleEvent*>(e) ;
      if (ee && ee->d()>=limit_) return false ;
      return true ;
    }
  private:
    double limit_ ;
  } ;

  int main() {
    Publisher* p = new Publisher ;
    S* s = new S ;

    igs_connect(p, s, igs_functor(s, S::event)) ;
    
    // Add the filter not to S but to the Listener
    Listener* l = igs_get_listener(p, s, igs_functor(s, S::event)) ;
    assert( l != NULL) ;
    l->add_event_filter(new SFilter(100)) ;
    
    p->igs_emit(DoubleEvent(50)) ;
    p->igs_emit(DoubleEvent(99)) ;
    p->igs_emit(DoubleEvent(100)) ; // never received
    p->igs_emit(DoubleEvent(200)) ; // never received
    p->igs_emit(DoubleEvent(1)) ;
  }
Will print:
  50
  99
  1



Frantz Maerten 2006-01-30