How to initialize static array member variable?

Sebastian Schuberth sschuberth at gmail.com
Thu Sep 30 23:35:06 PDT 2010


On 30.09.2010 22:01, Philippe Sigaud wrote:

> 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.

You're right, I want exactly N T's, but from reading the section about 
"Typesafe Variadic Functions" at [1], I thought I'm doing exactly that. 
The example "For static arrays" has a comment which says for a 
declaration like

int sum(int[3] ar ...)

this

return sum(2, 3); // error, need 3 values for array

would not work, so I thought "...", if following a statically sized 
array, is a special syntax to allow the array to be initialized from 
exactly N scalar values.

In fact, I checked that with my code

auto v=Vec3f(1,0,0);

compiles, but

auto v=Vec3f(1,0);
auto v=Vec3f(1,0,0,0);
auto v=Vec3f([1,0,0],[1,0,0]);

do not compile, just as desired. So I thought I'm doing the right thing :-)

> Which gives the following constructor:
>
> this(U...)(U v) if (U.length<= N&&  is(CommonType!U : T))
> {
>      data = [v];
> }

Well, this makes sense, thank you. I'm just wondering if my solution is 
any less safe?

> 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.

Thanks for all the hints!

> 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.

With tuples, would it still be that sizeof(Vector)==sizeof(T)*N?

[1] http://www.digitalmars.com/d/2.0/function.html

-- 
Sebastian Schuberth


More information about the Digitalmars-d-learn mailing list