What is a sink delegate?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 10 08:20:50 PDT 2014


On 10/10/2014 06:30 AM, Steven Schveighoffer wrote:

 > On 10/10/14 1:00 AM, Ali Çehreli wrote:
 >> On 10/09/2014 08:06 PM, Joel wrote:
 >>> On Tuesday, 30 September 2014 at 17:27:09 UTC, Adam D. Ruppe wrote:
 >>>> On Tuesday, 30 September 2014 at 17:22:44 UTC, Gary Willoughby wrote:
 >>>>> What is a sink delegate?
 >>>>
 >>>> Instead of
 >>>>
 >>>> string toString() { return "foo"; }
 >>>>
 >>>> for example, you would use:
 >>>>
 >>>> void toString(void delegate(string) sink) { sink("foo"); }
 >>>>
 >>>> The sink argument there is then free to view and discard the data or
 >>>> to make a private copy using whatever scheme it desires.
 >>>
 >>>
 >>> How do you use that toString? Maybe an example? Below is my failed
 >>> effort.
 >>>
 >>> import std.stdio;
 >>>
 >>> struct Try {
 >>>      string name;
 >>>      long age;
 >>>
 >>>      void toString(void delegate(string) sink) {
 >>>          sink("foo");
 >>>      }
 >>> }
 >>>
 >>> void main() {
 >>>      Try t = Try("Joel", 35);
 >>>      writeln(t);
 >>> }
 >>
 >> The signature of that toString is different from what I have been seeing
 >> and using. The following works:
 >>
 >>      void toString(void delegate(const(char)[]) sink) const {
 >
 > The delegate parameter is what is important. The function that is going
 > to be passed in takes a const(char)[],

That is what I meant.

 > which actually should, but does
 > not, implicitly cast to a delegate(string) (see issue
 > https://issues.dlang.org/show_bug.cgi?id=3075).
 >
 > 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. 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);
     }
}

void main()
{
     const c = S(42);
     writeln(c);
}

Add a const at the end, now it calls the user defined one.

 >
 > -Steve

Ali



More information about the Digitalmars-d-learn mailing list