digitalmars.D.learn - Initialization of structure field w/o default ctor
- drug (3/3) Jan 22 2015 What's the best way to initialize structure field that has no default ct...
- bearophile (20/21) Jan 22 2015 One solution:
- drug (2/23) Jan 22 2015 Yes, that's what the doctor prescribed. Thank you!
- Kenji Hara (17/52) Jan 22 2015 Or you can use block assignment in the constructor.
What's the best way to initialize structure field that has no default ctor? http://dpaste.dzfl.pl/64cd0a3879fa Also can I avoid "dummy" non-default ctor for Bar?
Jan 22 2015
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
Jan 22 2015
On 22.01.2015 15:30, bearophile wrote:drug:Yes, that's what the doctor prescribed. Thank you!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
Jan 22 2015
On Thursday, 22 January 2015 at 12:45:53 UTC, drug wrote:On 22.01.2015 15:30, bearophile wrote: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 Haradrug:Yes, that's what the doctor prescribed. Thank you!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
Jan 22 2015