Defining a single opCast disables explicit cast to base interfaces

Ali Çehreli via Digitalmars-d digitalmars-d at puremagic.com
Mon Mar 16 22:27:36 PDT 2015


The following program compiles fine:

interface I
{}

class B : I
{}

class C : B
{
     int i;
}

void main()
{
     auto c = new C;

     auto i = cast(I)c;    // compiles
     auto b = cast(B)c;    // compiles
}

Let's add an unrelated opCast to C:

class C : B
{
     int i;

     int opCast(T : int)()
     {
         return i;
     }
}

Now the last two lines of main fail to compile:

Error: template instance opCast!(I) does not match template declaration 
opCast(T : int)()
Error: template instance opCast!(B) does not match template declaration 
opCast(T : int)()

Is this per spec? (Actually, where is the spec? (Trick question. ;) )

There is a workaround: Add a catch-all opCast that forwards to the 
all-powerful std.conv.to:

     T opCast(T)()
     {
         import std.conv;
         return this.to!T;
     }

Now it compiles and works as expected.

However, the question remains...

Thank you,
Ali


More information about the Digitalmars-d mailing list