Can a member function return a delegate to itself?
teales
steve.teale at britseyeview.com
Wed May 23 21:29:32 PDT 2007
BCS Wrote:
> 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 mentioned, the reason this isn't directly doable is that the type is
> undefinable. However this is strictly a limitation of the D Syntax and
> their is no problem with actually doing it if you can tell DMD how. I
> have does this using typing tricks before:
>
>
> struct S
> {
> S delegate(int,int) dg;
> }
>
> struct O
> {
> int k;
> S go(int i, int j)
> {
> O* o = new O
> o.k = k+i+j;
> S ret;
> ret.dg = &o.go;
> return ret;
> }
> }
I also think your solution is nifty. So the answer to my question is rather like what you suggested, but you have to add an opCall to S, as in:
import std.stdio;
struct S
{
S delegate(int) dg;
S opCall(int n) { dg(n); return *this; }
}
struct O
{
int a;
S sum(int i)
{
a += i;
S ret;
ret.dg = ∑
return ret;
}
}
void main(char[][] args)
{
O o;
o.sum(1)(2)(3);
writefln("%d", o.a); // prints 6 as desired
}
It was just a curious question in the first place but you never know, somebody might find a use for it.
More information about the Digitalmars-d
mailing list