Signals and Slots in D

Walter Bright newshound at digitalmars.com
Thu Sep 28 18:17:41 PDT 2006


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?



More information about the Digitalmars-d mailing list