Small suggestion for default constructors

Ali Çehreli acehreli at yahoo.com
Tue Jan 17 16:49:55 UTC 2023


On 1/16/23 19:12, Adam D Ruppe wrote:
 >          // one little function
 >          this(typeof(this.tupleof) t) {
 >                  this.tupleof = t;
 >          }

Which can be mixed-in and can have default arguments:

mixin template memberAssigningConstructor() {
     // one little function
     this(typeof(this.tupleof) t = typeof(this.tupleof).init) {
         this.tupleof = t;
     }
}

import std.stdio;

class Foo {
     int x;
     int y;
     int z;

     mixin memberAssigningConstructor!();

     override string toString() const {
         import std.format : format;
         return format!"%s %s %s"(x, y, z);
     }
}

void testWith(Args...)(Args args) {
     auto f = new Foo(args);
     writeln(f);
}

void main() {
     testWith();
     testWith(1);
     testWith(1, 2);
     testWith(1, 2, 3);
}

Outputs:

0 0 0
1 0 0
1 2 0
1 2 3

However, I recommend testing compilation speeds because I used mixed-in 
tupleof for opCmp implementations in a project about 3 years ago. There 
were only 6 instances of that usage but the compilation times were 
noticeably affected. (Disclaimer: There were 6 instances but I think 
those modules were imported very many times by other modules.)

Replacing the tupleof idiom with trivial functions fixed the compilation 
speed issue for me.

Ali



More information about the Digitalmars-d mailing list