On Wednesday, 12 March 2014 at 10:57:10 UTC, Steve Teale wrote:
interface I
{
   auto myType();
}

class A: I
{
   auto myType() { return cast(A) null; }
}

void main()
{
   I x = getSomeI();
   typeof(x.myType()) y;
}

Check out: http://forum.dlang.org/thread/[email protected]
/ http://dpaste.dzfl.pl/6c90ca418996

It does what you want. As mentioned, you can't quite do this at compile time because the types must be known(or else just use object or a void *).

You can, though do this at runtime:

interface I
{
   I myType(); // can return anything that derives from I

}

class A : I
{
    final A _myType() { return cast(A) null; }

//mixin(AbstractToInterface!(A, I, A)); // (won't work as is because only return type of myType will be different. Need to use different names)

// The mixin would create the following function if slightly modified
    I myType() { return _myType; }
}

void main()
{
   I x = getSomeI();
   typeof(x._myType()) y1;
   typeof(x.myType()) y2;
   typeof(cast(Object)x.myType()) y;
}

y1 = y2 = I, y = A. (cast(Object) has to do with the weird way D handles interface types)

Note, that this code works in that if a new class B is created, it can return it's type:


class B : I
{
    final B _myType() { return cast(B) null; }
    I myType() { return _myType; }
}



If getSomeI() returns B then y = B.


Of course it's way easier just to do
typeof(cast(Object)x) y; unless you want to potentially return different objects.

Reply via email to