Any way to reproduce Dart style constructors?
Moritz Maxeiner via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu May 25 06:13:41 PDT 2017
On Thursday, 25 May 2017 at 12:35:57 UTC, Moritz Maxeiner wrote:
> On Thursday, 25 May 2017 at 11:31:43 UTC, ag0aep6g wrote:
>> On 05/25/2017 12:52 PM, Moritz Maxeiner wrote:
>>> Be aware, though, that constructors mixed in via a mixin
>>> template behave differently with regards to overloading[1].
>>>
>>> [1] https://issues.dlang.org/show_bug.cgi?id=11500
>>
>> Of course it couldn't be that simple :(
>>
>> Adam's workaround (`alias __ctor = mixin_thing.__ctor;`) might
>> be workable, though.
>>
>> If that makes the usage too verbose, then a string mixin is
>> the way to go, I guess. It's immune to issue 11500, but
>> AutoConstructor isn't as nice to look at:
>>
>> ----
>> static string AutoConstructor(fields ...)()
>> {
>> [...]
>> }
>> ----
>>
>> Weird: AutoConstructor needs to be static. Doesn't make sense
>> to me. Looks like a compiler bug.
>
> Nice. If you look at my initial reply to OP you'll see that I
> mentioned that error and I worked around it differently (worse
> than you). Didn't know that static would fix that (and I don't
> understand why it does), but thanks for the info!
After thinking about this a bit I think I know why it doesn't
work without static and it's not a compiler bug. Since
---
string AutoConstructor(fields ...)() {}
---
is just syntax sugar for
---
template AutoConstructor(fields ...)
{
string AutoConstructor() {}
}
---
instantiating the template AutoConstructor inside class Person
gives you a non-static member function AutoConstructor of class
Person, so obviously we need an instance of Person to call it on.
Or make it a static member function.
More information about the Digitalmars-d-learn
mailing list