Struggling trying to use opCast to solve the the interface impl VS the class impl

user1234 user1234 at 12.de
Sat Nov 8 10:04:45 UTC 2025


Following recent discussion in the General group, I had the idea 
to use `opCast` in order to return a specially cooked interface 
instance.

That would not be a decent solution because for example `opCast` 
template func is not virtual but nonetheless I'd like to know if 
this could work...

Only problem is that I cant manage to build the custom interface, 
or more exactly, it is not binary compatible:

```d
import core.stdc.stdio, core.memory;

interface CanStart
{
     void start();
}

class Base : CanStart
{
     public void start()
     {
         puts("object start()");
     }

     public void interfaceStart()
     {
         puts("itf start()");
     }

     T opCast(T)()
     {
         static if (is(T == CanStart))
         {
             auto s = GC.malloc(size_t.sizeof*2);
             auto r = cast(void**) s;
             r[0]   = cast(void*)this;  // likely the issue
             r[1]   = (&interfaceStart).ptr;
             auto result = *cast(CanStart*) s;
             assert(result);
             return result;

             //assert(0, "smthg can be done here...");
         }
         return cast(T) this;
     }
}

void main()
{
     scope b = new Base;
     b.start();

     scope cs = cast(CanStart) b;
     cs.start();
}
```


More information about the Digitalmars-d-learn mailing list