Named constructors

Simen Kjærås simen.kjaras at gmail.com
Thu Jan 10 07:06:51 UTC 2019


On Wednesday, 9 January 2019 at 20:54:48 UTC, JN wrote:
> On Wednesday, 9 January 2019 at 10:02:12 UTC, bauss wrote:
>>
>> I like this approach to it and you're entirely correct.
>>
>> It would be nice with support for this in the language without 
>> having to create factory methods.
>>
>> Basically something like the following could be lowered to 
>> your code.
>
> I was going to say that this post will be mostly ignored and 
> people will present some template magic to partially implement 
> such feature (just add few imports and some boilerplate code), 
> but I guess I got beaten to it :)

Since those templates are my specialty, here's my go:

struct Point {
     this(string s : "rectangular")(real x, real y) { /* ... */ }
     this(string s : "polar") (real r, real theta)  { /* ... */ }
}

struct make(T) {
     @disable this();
     static T opDispatch(string name, Args...)(Args args) {
         T result;
         result.__ctor!name(args);
         return result;
     }
}

unittest {
     auto a = make!Point.rectangular(1,2);
     auto b = make!Point.polar(1,2);
}

--
   Simen


More information about the Digitalmars-d mailing list