Initialization of structure field w/o default ctor

Kenji Hara via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jan 22 08:11:51 PST 2015


On Thursday, 22 January 2015 at 12:45:53 UTC, drug wrote:
> On 22.01.2015 15:30, bearophile wrote:
>> drug:
>>
>>> Also can I avoid "dummy" non-default ctor for Bar?
>>
>> One solution:
>>
>>
>> struct Foo {
>>     int foo;
>>
>>     @disable this();
>>
>>     this(int foo_) pure nothrow @safe @nogc {
>>         this.foo = foo_;
>>     }
>> }
>>
>> struct Bar {
>>     enum arraySize = 3;
>>
>>     Foo[arraySize] foo = Foo(1);
>> }
>>
>> void main() @safe {
>>     import std.stdio;
>>
>>     Bar bar;
>>     bar.writeln;
>> }
>>
>>
>> Bye,
>> bearophile
>
> Yes, that's what the doctor prescribed. Thank you!

Or you can use block assignment in the constructor.

struct Bar
{
     enum ArraySize = 3;

     Foo[ArraySize] foo;

     this(string dummy) // <== here because compiler demands to 
initialize field foo
     {
         import std.algorithm: fill;

         //fill(foo[], Foo(0));
         foo[] = Foo(0);   // <== OK
     }
}

Compiler can recognize the block assignment as a construction for 
the field Bar.foo.

Kenji Hara


More information about the Digitalmars-d-learn mailing list