Nicer syntax for constructors

Steven Schveighoffer schveiguy at gmail.com
Mon Nov 19 15:01:02 UTC 2018


On 11/18/18 3:06 PM, Trailzz wrote:
> On Sunday, 18 November 2018 at 19:59:27 UTC, Timon Gehr wrote:
>> On 18.11.18 20:52, Trailzz wrote:
>>> On Sunday, 18 November 2018 at 19:47:26 UTC, Jacob Carlborg wrote:
>>>> [...]
>>>
>>> This is still very clunky and hard to understand.
>>
>> ---
>> module util;
>> enum assignFields=q{{
>>     import std.traits;
>>     static foreach(x;ParameterIdentifierTuple!(__traits(parent,{})))
>>         static if(__traits(hasMember, this, x))
>>             __traits(getMember,this,x)=mixin(x);
>> }};
>> ---
>> ---
>> module app;
>> import util;
>>
>> class C{
>>     string a;
>>     int b;
>>     char c;
>>     float d;
>>     uint e;
>>     bool f;
>>     this(string a, int b, char c, float d, uint e, bool f){
>>         mixin(assignFields);
>>     }
>> }
>>
>> void main(){
>>     import std.stdio;
>>     writeln((new C("1",2,'3',4.0,5,true).tupleof));
>> }
>> ---
> 
> This is arguably more clunky than just lots of `this.foo = foo`.

Maybe you didn't notice that util module is written *once*, and then 
imported where used. All you would have to do is the one 
`mixin(assignFields)` line in the places you wanted this boiler plate.

To me, this is an elegant, simple solution, and IMO, actually nicer than 
any proposed language syntax changes (I find having to put `this` in 
front of all the parameter names just as clunky as doing the assignments).

-Steve


More information about the Digitalmars-d mailing list