Auto constructor [Was: Archetype language]

KennyTM~ kennytm at gmail.com
Mon Mar 21 03:09:20 PDT 2011


On Mar 21, 11 16:17, Don wrote:
> Daniel Gibson wrote:
>> Am 21.03.2011 00:55, schrieb bearophile:
>>> Among the things I've listed about Archetype there's one interesting
>>> thing. Class instances aren't PODs, but sometimes I prefer reference
>>> semantics and to populate fields in a plain way, expecially for
>>> simple classes.
>>>
>>> Time ago I and other people have suggested a syntax like (this also
>>> to avoid a class of bugs
>>> http://d.puremagic.com/issues/show_bug.cgi?id=3878 ):
>>>
>>>
>>> class Foo {
>>> string x;
>>> int y = 1;
>>> this(this.x, this.y) {}
>>> }
>>> void main() {
>>> Foo f3 = new Foo("hello", 10);
>>> }
>>>
>>
>> Yeah, I still like that idea ;)
>>
>>>
>>> A simpler solution are classes with automatic constructors:
>>>
>>> class Foo {
>>> string x;
>>> int y = 1;
>>> }
>>> void main() {
>>> Foo f1 = new Foo(); // Good
>>> Foo f2 = new Foo("hello"); // Good
>>> Foo f3 = new Foo("hello", 10); // Good
>>> }
>>>
>>>
>>> What kind of problems are caused by this? :-)
>>>
>>
>> You'd have to know the order in that the members are defined in the
>> class (and you may not change the order).
>> Just imagine
>> class Foo {
>> int bla;
>> int baz;
>> }
>>
>> new Foo(42, 3); // what is bla, what is baz?
>>
>> and then you decide "uh I'd prefer to have my class members ordered
>> alphabetically" and *bamm* all you code silently breaks.
>>
>> having a this(this.bla, this.baz) {} would clearly document which
>> argument in the constructor belongs to which class member and the
>> class members ordering wouldn't matter.
>>
>> Cheers,
>> - Daniel
>
> I agree. But unfortunately, the idea is a relatively complicated feature
> with a lot of special cases. For example, this(this.bla, this.bla){}

'int f(int x, int x) {}' is a syntax error. So should 'this(this.x, 
this.x){}'.

> and what if the class contains a union and you set multiple members of it?
> The whole thing is actually quite messy. It's not _terrible_, but it's
> far from trivial, and it's more complicated than some far more powerful
> and useful language features.
>

The syntax

     this(args, this.x.y.z, args, this.p.q.r = s, arg = t)
     {
        statements;
     }

could just lower to

     this(args, typeof(this.x.y.z) z, args, typeof(this.p.q.r) r = s, 
arg = t)
     {
        this.x.y.z = z;
        this.p.q.r = r;
        statements;
     }

Would this be too complicated?

(Not that I like this idea... But I think it is not really that messy)


More information about the Digitalmars-d mailing list