On Friday, 10 October 2014 at 01:32:54 UTC, dcrepid wrote:
On Sunday, 27 November 2011 at 19:50:24 UTC, deadalnix wrote:
Hi,
I wonder why struct can't have a default constructor...
I know this is an old thread, but I've run into this same
problem recently and search yielded this result.
I myself have tried working around the default-constructor
problem with things like
this(bool bInit = true)
- which of course doesn't get invoked with MyStruct(), even
with @disable this.
You can use `static opCall` as a workaround. The following prints
"S(0)" and "S(3)":
struct S {
int x;
static S opCall() {
S s;
s.x = 3;
return s;
}
}
void main() {
import std.stdio;
S s;
writeln(s);
S t = S();
writeln(t);
}
But if you add a constructor with parameters, you get an error:
struct S {
int x;
static S opCall() { ... }
this(int y) { x = y; }
}
xx.d(4): Error: struct xx.S static opCall is hidden by
constructors and can never be called
xx.d(4): Please use a factory method instead, or replace
all constructors with static opCall.
IMO this is too restrictive, as obviously, the static opCall is
_not_ hidden by the constructor.