Signals and Slots in D
J Duncan
me at nospam.com
Thu Sep 28 18:53:42 PDT 2006
Lutger wrote:
> 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.
Yeah thats pretty much it, everything can be done with templates etc.
What we dont really have yet is a standardized introspection. One of the
nice things about qt is it provides a typesafe callback which c++ doesnt
have. D has the Wonderful delegate, so at least we get builtin typesafe
callbacks. But on my D wishlist is introspection - or a builtin
messaging system, or at least a standardized implementation in phobos.
But its not a big deal by any means, I just think people who have used
qt see how s&s would be Very Cool in D.
More information about the Digitalmars-d
mailing list