Any way to reproduce Dart style constructors?

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 25 12:09:06 PDT 2017


On 05/25/2017 08:14 PM, Moritz Maxeiner wrote:
> Well, then I guess we need a compiler guy to clear this up, because from 
> my point of view, the template is instantiated within the scope of the 
> class (way before we reach the mixin), nesting the template's scope 
> within the class' scope, which makes the function within that template's 
> scope a member function of the class.

You get a very similar error when you instantiate outside:

----
class Person { int age; }
string AutoConstructor(fields ...)() { return ""; }
enum s = AutoConstructor!(Person.age);
     /* Error: need 'this' for 'AutoConstructor' of type 'string()' */
----

So I don't think it has anything to do with having the instantiation 
inside the class. Passing a class member to a function template seems to 
be the trigger. But it's more complicated than that. The instantiation 
itself goes through. The error only occurs when you actually call the 
function.

Also, simply instantiating a function template inside a class doesn't 
result in a method. If it did, the function/method should be able to 
access class members. But it can't:

----
int ft()() { return age; } /* Error: undefined identifier age */
class Person
{
     int age = 42;
     alias method = ft!(); /* error instantiating */
}
----


More information about the Digitalmars-d-learn mailing list