Any way to reproduce Dart style constructors?

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 25 03:42:00 PDT 2017


On 05/25/2017 10:34 AM, JN wrote:
> class Person
> {
>    string name;
>    int age;
>    mixin(AutoConstructor!(age, name));
> }
[...]
> I am not looking for code, I can try that myself, just asking if such 
> things are possible?

I know you're not asking for code, but without experimenting I wouldn't 
have known that this works. In the end it's surprisingly simple:

----
mixin template AutoConstructor(fields ...)
{
     this(typeof(fields) args) { fields = args; }
}

class Person
{
     string name;
     int age;
     mixin AutoConstructor!(age, name);
}

void main()
{
     auto p = new Person(42, "Arthur");
     assert(p.age == 42);
     assert(p.name == "Arthur");
}
----


More information about the Digitalmars-d-learn mailing list