Thread overview
Initialising arrays at compile time
Jan 02, 2011
Peter Alexander
Jan 02, 2011
bearophile
Jan 02, 2011
Peter Alexander
Jan 05, 2011
so
Jan 05, 2011
bearophile
January 02, 2011
Ok, someone put me out of my misery, I can't figure out for the life of me how to do this. Basically, I have a vector class and want enums for the zero vectors:

struct Vec
{
  this(real x, real y) { e[0] = x; e[1] = y; }
  real[2] e;
  enum Vec zero = Vec(0, 0);
}

What can I do?

The above doesn't work because:

test.d(3): Error: Index assignment this.e[0u] = x is not yet supported in CTFE
test.d(3): Error: Index assignment this.e[1u] = y is not yet supported in CTFE


Changing the constructor to do e = [x, y] doesn't work either.

test.d(3): Error: Slice operation this.e[] = [x,y] cannot be evaluated at compile time
test.d(5): Error: cannot evaluate __ctmp1.this(0L,0L) at compile time
test.d(5): Error: cannot evaluate __ctmp1.this(0L,0L) at compile time


What can I do?

And once I do that, I need to do it also for:

struct Vec(int N)
{
  real[N] e;
  ...
}

Thanks in advance.
January 02, 2011
Peter Alexander:

> Ok, someone put me out of my misery, I can't figure out for the life of me how to do this. Basically, I have a vector class and want enums for the zero vectors:
> 
> struct Vec
> {
>    this(real x, real y) { e[0] = x; e[1] = y; }
>    real[2] e;
>    enum Vec zero = Vec(0, 0);
> }

Is this good enough?

struct Vec {
    double[2] e;

    static enum Vec zero = Vec([0.0, 0.0]);

    this(real x, real y) {
        e[0] = x;
        e[1] = y;
    }
}

void main() {}

(I think that "enum" and "static enum" are the same thing.)

Bye,
bearophile
January 02, 2011
On 2/01/11 2:16 PM, bearophile wrote:
> Is this good enough?
>
> struct Vec {
>      double[2] e;
>
>      static enum Vec zero = Vec([0.0, 0.0]);
>
>      this(real x, real y) {
>          e[0] = x;
>          e[1] = y;
>      }
> }

Well it works, so yes :-)

That's quite irritating. Why does the automatically generated one work, but not the hand written one. Grrr...

I also discovered that this works:

enum Vec zero = Vec([0.0, 0.0]);

this(double[2] v)
{
  foreach (size_t i, ref r; e)
    r = v[i];
}

Which works in the general case of an arbitrary sized vector.
January 05, 2011
> (I think that "enum" and "static enum" are the same thing.)

"static enum" makes no sense, shouldn't it be an error?

-- 
Using Opera's revolutionary email client: http://www.opera.com/mail/
January 05, 2011
so:

> "static enum" makes no sense, shouldn't it be an error?

Currently the way D/DMD manages attributes and the like is so sloppy that it seems trash. But there are always more important things to do and fix, so no care is given on this problem:
http://d.puremagic.com/issues/show_bug.cgi?id=3934
My theory is: if the compiler is very sloppy then language newbies will have to work twice harder to learn what's correct and what's wrong.

Bye,
bearophile