how to make new C return other static type than C

Adam D. Ruppe destructionator at gmail.com
Sun Dec 9 10:33:39 PST 2012


On Sunday, 9 December 2012 at 18:23:15 UTC, deed wrote:
> - Is it possible to enforce, from within the class, a certain 
> static interface type or ancestor type when instantiating with 
> new? If so, how is it done?

No, but you could make the constructor private so new doesn't 
work on it at all, and then use a factory function.

     static I make() { return new C(); }
     private this() {}

     auto obj = new C; // won't compile
     auto obj2 = C.make(); // works, obj2 static type is I

The make function could be a template or whatever and change the 
return type that way.


And, of course, don't forget

I obj = new C();

will always type obj as the interface.


More information about the Digitalmars-d-learn mailing list