hacky way to get explicit default constructor on struct :P

Steven Schveighoffer schveiguy at yahoo.com
Mon Oct 30 13:24:46 UTC 2017


On 10/28/17 12:59 PM, LunaticWare wrote:
> Event if there is no default constructor on struct we can still make one 
> that work as well as if it were implemented, here is my example n__n
> 
> ------
> 
> import std.format;
> import std.stdio;
> 
> struct Player
> {
>      string name = "Baz";
>      float[2] position = [0, 0];
> 
>      // Adding an explicit constructor to struct =)
>      // But we can't enforce it since this relies on it =(
>      static ref auto opCall(string name = "Bar", float x = 1, float y = 1)
>      {
>          // Even if we give no argument opCall will still be called ;)
>          writefln("Entering the explicit constructor as '%s'", name);
> 
>          // Taking advantage of the implicit constructor
>          Player self;
> 
>          // Initializing all the members
>          self.name = name;
>          self.position[0] = x;
>          self.position[1] = y;
> 
>          // Returning the reference of the object
>          return self;
>      }
> 
>      string toString()
>      {
>          return format("Hello i am '%s' and at the coordinate x%s / y%s",
>              this.name, this.position[0], this.position[1]);
>      }
> }
> 
> void main()
> {
>      auto foo = Player("Foo", 2.7, 10.6);
>      auto bar = Player();
>      Player baz;
> 
>      writefln("%s\n%s\n%s", foo, bar, baz);
> }
> 
> // == RDMD OUTPUT ==
> // Entering the explicit constructor as 'Foo'
> // Entering the explicit constructor as 'Bar'
> // Hello i am 'Foo' and at the coordinate x2.7 / y10.6
> // Hello i am 'Bar' and at the coordinate x1 / y1
> // Hello i am 'Baz' and at the coordinate x0 / y0
> 

You won't ever get the same support for this as C++. D is very clear 
that a struct must be constructable from its init value, and be valid.

For instance:

auto p = new Player[1];
assert(p[0].name == "Baz");

-Steve


More information about the Digitalmars-d mailing list