On Monday, 24 February 2014 at 17:15:10 UTC, Remo wrote:

Well fortunately it seems to be possible to override init property.

Fortunately? I think not. It's an abomination that, IMO, has to be annihilated. Recently Andrei suggested adding more explicit semantics to .init that may give some leeway in this matter, although this was concerning classes and non-null default values, so it may not concern structs at all. Regardless, my advice - don't try to override .init, i.e. don't invite trouble into your code :)

But it still does not called at struct construction.
http://melpon.org/wandbox/permlink/9EvcdzKUKoufqbJa

Yup.

So what is proper/best way to mimic default constructor for struct ?

Don't do it. Default construction for struct *is* initialization of its fields. If you want to do something other that initialize fields - create a function and call it explicitly. D is not C++, don't expect it to behave identically. To make it easier when porting code, you can always temporarily @disable this() so the compiler will stop whenever you'd use your "special" default construction in C++.

As you've mentioned, the code from your example doesn't need any special default constructors at all, this will work just fine:

struct Vector(T) {
    T x = 0, y = 0, z = 0;

    this(T v) { x = y = z = v; }
    this(T x, T y, T z) { this.x = x; this.y = y; this.z = z; }
}


unittest {
    Vector!double v;
    auto v2 = Vector!double(1);
    auto v3 = Vector!double(1,2,3);

    assert(v.x == v.y && v.y == v.z && v.z == 0);
    assert(v2.x == v2.x && v2.y == v2.z && v2.z == 1);
    assert(v3.x == 1 && v3.y == 2 && v3.z == 3);
}


Also please take a look at those:

https://d.puremagic.com/issues/show_bug.cgi?id=3438
https://d.puremagic.com/issues/show_bug.cgi?id=6080
https://d.puremagic.com/issues/show_bug.cgi?id=7066
https://d.puremagic.com/issues/show_bug.cgi?id=7597
https://d.puremagic.com/issues/show_bug.cgi?id=8816
https://d.puremagic.com/issues/show_bug.cgi?id=8817
https://d.puremagic.com/issues/show_bug.cgi?id=10413
https://d.puremagic.com/issues/show_bug.cgi?id=11307

There may be some others I've missed; the sheer amount and unresolved state is terrifying.

Reply via email to