Can't understand the application of delegates in toString() functions
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Nov 7 08:54:06 PST 2016
On 11/07/2016 08:40 AM, Heisenberg wrote:
> On Monday, 7 November 2016 at 16:33:30 UTC, Adam D. Ruppe wrote:
>> On Monday, 7 November 2016 at 16:22:17 UTC, Heisenberg wrote:
>>> Why? How can a delegate which returns nothing be used as an array
>>> which is going to be printed on the screen?
>>
>> You pass the string to the delegate, which does whatever with it
>> somewhere else.
>>
>> So you call: `passed_delegate("your string");` and it can forward it
>> to writeln or whatever.
>
> But how does it forward it if it's:
>
>> void delegate(const(char)[]) sink // ?
>
> It returns nothing, and just takes an array of characters as a
> parameter.. Just how does it print?..
Exactly how it happens requires explaining a long chain of function
calls. Probably that's why the author did not elaborate further. ;) I've
probably omitted some steps here but I think the following is close enough:
- writeln() that's in the sample code calls write() with the addition of
'\n'.
- write() eventually calls formattedWrite() with a lockingTextWriter as
the writer:
https://github.com/dlang/phobos/blob/master/std/stdio.d#L1401
- formattedWrite() calls formatValue():
https://github.com/dlang/phobos/blob/master/std/format.d#L2906
- formatValue() calls formatObject() and that's the one that makes a
distinction between different overloads of toString():
https://github.com/dlang/phobos/blob/master/std/format.d#L2805
- formatObject() calls put(), which finally uses the 'sink' parameter as
an output range and fills in with characters.
Ali
More information about the Digitalmars-d-learn
mailing list