How to initialize static array member variable?

Jonathan M Davis jmdavisProg at gmx.com
Thu Sep 30 13:04:09 PDT 2010


On Thursday 30 September 2010 12:14:09 Sebastian Schuberth 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];
> };
> 
> alias Vector!(3,float) Vec3f;
> 
> gives
> 
> Error	1	Error: Slice operation this.data[] = cast(const(float[]))v
> cannot be evaluated at compile time		main.d	6
> 
> I also tried simply
> 
> struct Vector(alias N,T)
> {
>      static immutable Vector X=Vector(1,0,0);
> 
>      this(T x,T y,T z) {
>          data[0]=x;
>          data[1]=y;
>          data[2]=z;
>      }
> 
>      T data[N];
> };
> 
> alias Vector!(3,float) Vec3f;
> 
> but that gives
> 
> Error	1	Error: Index assignment this.data[0u] = x is not yet supported
> in CTFE		main.d	6
> Error	2	Error: Index assignment this.data[1u] = y is not yet supported
> in CTFE		main.d	7
> Error	3	Error: Index assignment this.data[2u] = z is not yet supported
> in CTFE		main.d	8
> 
> Any other ideas how to introduce such an "X" constant?
> 
> Thanks.

You could initialized it in a static constructor. e.g.

static this()
{
	X = Vector(1, 0, 0);
}

By the way, it's a bit atypical in D at this point to declare constants in all 
caps - primarily because you often end up with so many in your code that it can 
get pretty ugly to have so many variables in all caps.

Also, assuming that you could initialize the variable at compile-time (which you 
obviously having trouble doing here), the typical way to declare such a constant 
is not to use static but rather enum. e.g.

enum x = Vector(1, 0, 0);

However, since you can't initialize this particular variable at compile-time as 
it stands, a static variable would be the correct way to go here.

Also, if you declare a variable immutable and initialize directly (as opposed to 
using a destructor), you don't have to include the type (just like you don't 
have to include the type for enum). Of course, since you need a static 
constructor here, it won't work here, but I thought that I'd let you know.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list