Signals and Slots in D

Lutger lutger.blijdestijn at gmail.com
Thu Sep 28 18:33:07 PDT 2006


Walter Bright wrote:
> Ok, I admit I don't understand S&S. But let's try starting with Qt's 
> canonical example from http://doc.trolltech.com/3.3/signalsandslots.html:
> 
>     class Foo : public QObject
>     {
>         Q_OBJECT
>     public:
>         Foo();
>         int value() const { return val; }
>     public slots:
>         void setValue( int );
>         {
>           if ( v != val ) {
>             val = v;
>             emit valueChanged(v);
>           }
>         }
>     signals:
>         void valueChanged( int );
>     private:
>         int val;
>     };
> 
>     Foo a, b;
>     connect(&a, SIGNAL(valueChanged(int)), &b, SLOT(setValue(int)));
>     b.setValue( 11 ); // a == undefined  b == 11
>     a.setValue( 79 ); // a == 79         b == 79
>     b.value();        // returns
> 
> It seems that I can do this in D with:
> 
>     class Foo
>     {
>         this();
>         int value() { return val; }
> 
>         void setValue( int );
>         {
>           if ( v != val ) {
>             val = v;
>             valueChanged(v);
>           }
>         }
> 
>         void valueChanged( int i )
>     {
>         foreach (dg; slots)
>         dg(i);
>     }
> 
>     void connect( void delegate(int i) dg)
>     {
>         slots ~= dg;
>     }
> 
>     private:
>     void delegate(int i)[] slots;
> 
>         int val;
>     };
> 
>     Foo a = new Foo;
>     Foo b = new Foo;
>     a.connect(&b.setValue);
>     b.setValue( 11 ); // a == undefined  b == 11
>     a.setValue( 79 ); // a == 79         b == 79
>     b.value();        // returns 79
> 
> There's no casting, it's statically typesafe. Some of the boilerplate 
> can be eliminated with a mixin. Is that all there is to it, or have I 
> completely missed the boat?

Almost, it's very simple, like the plain old function pointer as 
callback in C. The main difference is:
- when an object which has member functions connected gets detroyed, 
there is no problem, no segfaults.
- signals and slots are not as tightly coupled to a specific class as in 
your example. Be it through introspection or ifti, class B needs to know 
nothing about A except where it can connect, meaning more less coupling 
between classes. I think thats all there is to it in essence.



More information about the Digitalmars-d mailing list