How would you implement this in D? (signals & slots)

Atila Neves via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 2 07:59:06 PST 2016


On Tuesday, 2 February 2016 at 14:49:21 UTC, Gerald wrote:
> On Monday, 1 February 2016 at 21:44:28 UTC, Enjoys Math wrote:
>> On Monday, 1 February 2016 at 21:40:45 UTC, Enjoys Math wrote:
>>> module signals_and_slots;
>>>
>>> import std.algorithm: remove;
>>>
>>> [...]
>>
>>
>> D's signals & slots:
>>
>> https://dlang.org/phobos/std_signals.html
>
> I looked at that and perhaps I'm not reading the exampes 
> correctly but I'm not sure how useful std.signals is in the 
> real world. If you have a bunch of slots which take the same 
> parameter types, not unusual in the GUI world, how would that 
> work?

Switch on the value inside the slot. Or use different types by 
wrapping, say, an int or a string with a struct:


import std.stdio;
import std.signals;


struct String1 { string s; }
struct String2 { string s; }

class Observer {
     void watch1(String1) { writeln("watch1"); }
     void watch2(String2) { writeln("watch2"); }
}

class Signals {
     mixin Signal!String1;
     mixin Signal!String2;
}


void main() {
     auto o = new Observer;
     auto s = new Signals;
     s.connect(&o.watch1);
     s.connect(&o.watch2);
     s.emit(String1("foo"));
     s.emit(String2("bar"));
}

> The other thing that bugs me is lack of naming for slots and 
> signals, again in the GUI world where you typically have dozens 
> of these on an an individual widget differentiation is quite 
> important.

Slots are named: the methods are slots. Signals can be named if 
you use only one struct as the parameter, as above. The signals 
would be String1 and String2, the slots watch1 and watch2.

Atila


More information about the Digitalmars-d-learn mailing list