Can we just have struct inheritence already?

Random D user no at email.com
Fri Jun 14 20:56:50 UTC 2019


On Thursday, 13 June 2019 at 22:12:37 UTC, Manu wrote:
> what is a 'static' interface?

I would define it as something like this:

static interface Processor
{
   // Required methods for a struct
   void prepare(Options opts);
   void process(ubyte[] data);
   bool isReady();
   Result get();

   int integer; // No size, just a requirement
}

struct IncorrectProcessor : Processor
{
   void prepare(Options opts) { ... }
   void doSomething() { ... }
}

// Implements all that's in the 'static interface' even the 
(public) data.
struct CorrectProcessor : Processor
{
   void prepare(Options opts) { ... }
   void process(ubyte[] data) { ... }
   bool isReady() { ... }
   Result get() { ... }

   int integer;

   void doSomething2() { ... }
   void doSomething3() { ... }
}

void myProcessorUseCase(Processor p)
{
   p.prepare(opts);
   p.process(data);
   while(!p.isReady()) { ... }
   return p.get();
}

// You can now call myProcessorUseCase with different types of 
processors with in different parts of code. No runtime type 
switching, no virtuals.

myProcessorUseCase( incorrectProcessor ); // Error: 
'incorrectProcessor' doesn't implement static interface 
'Processor' correctly

myProcessorUseCase( correctProcessor ); // OK

-----
Basically, a static compile-time check that struct is of specific 
form. Kind of like compiling a different .c file for a 
shared/interface .h file for different builds, except not 
restricted to files and builds.
No virtuals or anything. Compiling doesn't produce any artifacts 
just does the check.

I've often wished for a feature like this. I suppose you can do 
template constraints, static ifs and meta, but honestly I find 
the result cumbersome and not very readable/debuggable.



More information about the Digitalmars-d mailing list