Can a member function return a delegate to itself?

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Wed May 23 07:05:05 PDT 2007


Steve Teale wrote:
> Something like:
> 
> class Foo
> {
>     int a;
> 
>     this() { a = 0; }
> 
>     void delegate(int) sum(int n) 
>               { a += n; return cast(void delegate(int)) &this.sum; }
> }

As said this can't be done because the return type of such a function 
would be it's own type, and so any description of the type would need to 
include itself as a (strict) substring. A type that cannot be described 
cannot be used.
However, there's a workaround:
---
class Foo
{
     int a;

     this() { a = 0; }

     // you can also put this into a struct member named "sum"
     // if you prefer
     Foo opCall(int n)
               { a += n; return this; }

     alias opCall sum;  // optional
}


// test code:
import std.stdio;

void main() {
	scope foo = new Foo;
	foo.sum(1)(2)(3);
	writefln(foo.a);        // writes '6'
}
---
(also popular with structs instead of classes. Or struct members of classes)



More information about the Digitalmars-d mailing list