Would love to override default ctor of struct

Meta jared771 at gmail.com
Mon Jan 21 20:50:45 UTC 2019


On Monday, 21 January 2019 at 19:08:49 UTC, Alex wrote:
> Could you give an example, where a zero argument construction 
> has to be done, which cannot be accomplished by setting the 
> appropriate field with a default value?

For the following reason, although the default argument 
constructor hack no longer works:

import std.stdio;

struct Test(bool useFieldDefaultVal)
{
     static if (useFieldDefaultVal)
     {
         int[] arr = [1, 2, 3];
     }
     else
     {
         int[] arr;

         this(int dummy = 0)
         {
             arr = [1, 2, 3];
         }
     }

     void doTest()
     {
     	writeln("Address of arr: ", arr.ptr);
     }
}

void main()
{
     Test!true t1;
     Test!true t2;

     // Deprecation: constructor `onlineapp.Test!false.Test.this`
     // all parameters have default arguments, but structs cannot
     // have default constructors.
     auto t3 = Test!false();

     t1.doTest(); // Prints "Address of arr: 5622DAA0F010"
     t2.doTest(); // Prints "Address of arr: 5622DAA0F010"
     t3.doTest(); // Prints "Address of arr: null"
}


More information about the Digitalmars-d mailing list