Suggestion: signal/slot mechanism

Lutger lutger.blijdestijn at gmail.com
Sat Sep 2 04:20:22 PDT 2006


Kristian wrote:
> It would be nice if D had a signal/slot mechanism similiar to Qt:
> http://doc.trolltech.com/4.1/signalsandslots.html
> 
> It's an elegant way to handle messages sent between objects. It beats 
> event table declarations used by other GUI libraries IMHO.
> 
> It would make D a lot more appealing language to write GUI applications. 
> Think of wxWidgets written in D... ;)
> 
> 
> I think it would be quite simple to build a S/S support for a compiler 
> (at first glance, at least). For example:
> 
> The 'Object' class has a pointer to S/S data (it's null if the object 
> don't currently use signals/slots). S/S data holds a slot list for each 
> signal. It also holds a list of objects that have slot(s) connected to 
> this object's signal(s). This list is used to disconnect necessary slots 
> at a destruction of the object.
> 
> When the compiler reads a 'emit X' statement, it will do two things. 
> First, it generates an id for the signal which is used to retrieve a 
> correct slot list.
> 
> Second, the compiler puts the signal's parameters to the stack as it 
> would call a corresponding function. Instead, the 
> 'Object._emit_signal(id)' function (or something) is called, where 'id' 
> is the generated id. (Note that there are no function bodies for 
> signals.) '_emit_signal()' retrieves the correct slot list, and calls 
> all the slots (delegates) in it. Finally the parameters are removed from 
> the stack.
> 
> Of course, slots should not modify their parameters so that all the 
> slots will receive the same parameter values. Hence slots should not use 
> the 'out type'. There is a market for a 'const type' here... *wink*
> 
> 
> Maybe there should be no slot keyword at all as there is in Qt. You 
> don't need to declare a function to be a slot; all the (virtual) 
> functions can be used with signals.
> 
> Because the return values of all the signals are void, the void typeword 
> could be removed from signal declarations.
> 
> signal clicked();
> 
> signals:
> clicked();
> clicked(int button);
> 
> 
> BTW, Qt generates ids for signals as follows:
> 
> signals:
> void clicked(int button, bool isMoved);
> -> the id is a string "clicked(int,bool)"

I agree the signal-slot mechanism is nice, but why must it be supported 
by a compiler? There a lots of good libraries in C++ for this, such as 
sigslots, libsigc++ and boost::signals. It is not necessary to have 
extra preprocessor or language support.

It should be possible to do this in a D library. There already is 
dcouple at dsource, but it is inactive. I have been working on a 
signal-slot module myself, the only thing missing now is automatic 
disconnections of which I am not sure how and if to proceed.



More information about the Digitalmars-d mailing list