struct init property
Ali Çehreli
acehreli at yahoo.com
Thu Aug 23 10:30:54 PDT 2012
On 08/23/2012 10:15 AM, nocide wrote:
> struct has no default constructor and instances are initialized with the
> init property.
> Can I declare or override the init property for a custom defined struct?
>
You can define the initial values of each member:
struct S
{
int i = 42;
double d = 1.5;
}
void main()
{
assert(S.init == S(42, 1.5));
}
That changes the .init value. You can also define a static opCall() to
mimic the default constructor. Note that this method does not affect the
.init value:
struct S
{
int i;
double d;
static S opCall()
{
S s;
s.i = 42;
s.d = 1.5;
return s;
}
}
void main()
{
assert(S().i == 42);
assert(S().d == 1.5);
assert(S.init.i == int.init);
import std.math;
assert(isnan(S.init.d));
}
Note that the static opCall() disables calling automatic destructor
(i.e. the S(1, 2) does not work anymore). I am not sure whether that is
one of the many struct-related issues at the moment.
Ali
More information about the Digitalmars-d-learn
mailing list