On Tuesday, 6 September 2016 at 13:44:37 UTC, Ethan Watson wrote:
So now I'm in a bind. This is one struct I need to construct
uniquely every time. And I also need to keep the usability up
to not require calling some other function since this is
matching a C++ class's functionality, including its ability to
instantiate anywhere.
Suggestions?
I know you don't like the explicit function-calling way, but I
think it is actually quite good, if you consider what the
compiler does and doesn't allow
e.g.
struct S
{
int a;
@disable this();
private this(int a) // just for ease of use in `create`
{
this.a = a;
}
static create() // could be free function instead
{
auto x = runtimeGetMySuperImportantUniqueValue();
return(S(x));
}
}
struct S1
{
S s; // fine despite @disable this()
// blah blah other state
this(int argForOtherState)
{
// if you comment this out, it doesn't compile,
// the compiler enforces initialisation for s
// because of @disable this()
s = S.create();
// blah blah other construction
}
}
void main()
{
// S1 s1; // doesn't compile, would bypass initialisation of s1.s
S1 s1 = S1(-1); // OK
}