| Thread overview | ||||||
|---|---|---|---|---|---|---|
|
January 22, 2015 Initialization of structure field w/o default ctor | ||||
|---|---|---|---|---|
| ||||
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? | ||||
January 22, 2015 Re: Initialization of structure field w/o default ctor | ||||
|---|---|---|---|---|
| ||||
Posted in reply to drug | 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
| |||
January 22, 2015 Re: Initialization of structure field w/o default ctor | ||||
|---|---|---|---|---|
| ||||
Posted in reply to bearophile | 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!
| |||
January 22, 2015 Re: Initialization of structure field w/o default ctor | ||||
|---|---|---|---|---|
| ||||
Posted in reply to drug | 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
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply