How to initialize static array member variable?

Philippe Sigaud philippe.sigaud at gmail.com
Thu Sep 30 13:01:17 PDT 2010


On Thu, Sep 30, 2010 at 21:14, Sebastian Schuberth <sschuberth at gmail.com> wrote:
> Hi,
>
> I'm still playing around with DMD 2.049 and my Vector struct. This
>
> struct Vector(alias N,T)
> {
>    static immutable Vector X=Vector(1,0,0);
>
>    this(T[N] v ...) {
>        data=v;
>    }
>
>    T data[N];
> };

To me, your constructor's signature is saying: "give me any number of
T[N]", which I guess is not what you want. You want exactly N T's.
Which gives the following constructor:

this(U...)(U v) if (U.length <= N && is(CommonType!U : T))
{
    data = [v];
}

I guess I'll have to explain this: U... is a bunch of values of any
type. With the template constraint I just check that
1) there is the correct number of values (at most N)
2) they can all be changed into T's

as for the  = [v] part, it's just that throwing a tuple in an array
constructor will make an array from the tuple.

Btw, "alias N" is a bit dangerous: N could be any symbol. As you use
it as a size, let's give it a size type:  Vector(int N, T) or
Vector(size_t N, T).
Also, T data[N]; is using a C syntax. In D, the idiomatic syntax is T[N] data;
And there is no need for a semicolon at the end of a struct
definition: the compiler knows it ends there.

Which gives us:

import std.traits: CommonType;

struct Vector(size_t N,T)
{
    this(U...)(U v) if (U.length <= N && is(CommonType!U == T))
    {
        data = [v];
    }

    T[N] data;
}


> Any other ideas how to introduce such an "X" constant?

It's doable, but it means modifying your struct a bit: instead of
holding the values in an array, you can store them in a tuple.
I'll see if anyone as another idea: I'm biased towards tuples.

Philippe


More information about the Digitalmars-d-learn mailing list