Declaring interfaces with a constructor

evilrat via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Mar 13 19:14:53 PDT 2017


On Monday, 13 March 2017 at 19:31:52 UTC, David  Zhang wrote:
>
> Basically, I want to define a common interface for a group of 
> platform-specific classes, except that they should ideally also 
> share constructor parameters. What I want to do is then alias 
> them to a common name, selecting the implementation for the 
> target platform at compile time.

like this?
--------------------------------------
import std.stdio;

abstract class PublicInterface
{
     this(int, int) {} // must have body, see below
}

version(broken) {
  alias ActualImpl = NotCompile;
}
else {
  alias ActualImpl = PlatformSpecificClass;
}

// put behind version too, this just for demonstration
class PlatformSpecificClass : PublicInterface
{
     this(int a, int b)
     {
         super(a,b); // yeah, downside of this approach
         writeln(a,b);
     }
}

version(broken) {
  class NotCompile : PublicInterface
  {
   // no interface ctor
  }
}

void main()
{
new ActualImpl(1,2);
}
-----------------------------------------

there is also way to do this using templates and duck typing, I 
think it will be more idiomatic way since ranges and stuff 
heavily use it to provide such generalism, though just like you 
say, I would prefer to have strict interface for such use case...


More information about the Digitalmars-d-learn mailing list