What is a sink delegate?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 10 10:00:46 PDT 2014


On 10/10/14 11:20 AM, Ali Çehreli wrote:
> On 10/10/2014 06:30 AM, Steven Schveighoffer wrote:
>
>  > The const outside is irrelevant to whether it will accept it or not,
>  > that is a contract between the toString function and your object. If you
>  > want a non-const toString, I think that should work.
>  >
>  > (actually, testing it...) Yep, it works without the const on the
> outside.
>
> But not for const objects.

I think that's what I said :) It's a contract between the toString 
function and your object, it has nothing to do with writeln accepting 
the function. There are some quirky requirements for certain "magic" 
functions in phobos that have to be exactly a certain signature for the 
compiler to use it.

Now, obviously, the toy example can be labeled const. But not one that 
might, say, cache some state in order to compute the output.

> The following program does not call the user
> defined toString:
>
> import std.stdio;
> import std.conv;
>
> struct S
> {
>      int i;
>
>      void toString(void delegate(const(char)[]) sink)
>      {
>          sink(i.to!string);

Don't do this. Do this instead:

import std.format;
sink.formattedWrite(i);

The former allocates memory on the heap, just to throw it away. You are 
completely losing the benefit of the sink.

-Steve


More information about the Digitalmars-d-learn mailing list