On Friday, 8 November 2013 at 02:13:01 UTC, Ross Hays wrote:
My end goal is to be able to instantiate a vector with a syntax
like...
`Vector!(2, float) vec = new Vector!(2, float)();`

...

Any suggestions?

Greetings,

This works:

---
import std.stdio;

struct Vector(int N, T) if (N <= 3) {
  private T[N] data;

  public @property
void opDispatch(string fieldName, Args ...)(Args args) if (Args.length == 1 && fieldName.length == 1 && cast(size_t)(fieldName[0] - 'x') < N) {
    static immutable offset = cast(size_t)(fieldName[0] - 'x');
    data[offset] = args[0];
  }

  public @property
T opDispatch(string fieldName, Args ...)(Args args) if (Args.length == 0 && fieldName.length == 1 && cast(size_t)(fieldName[0] - 'x') < N) {
    static immutable offset = cast(size_t)(fieldName[0] - 'x');
    return data[offset];
  }
}

void main() {
  auto vec = Vector!(2, float)();
  vec.x = 1.0;
  vec.y = 2.0;
//vec.z = 3.0; // Doesn't compile, as expected for a Vector!(2, float);

  writeln("vec.x = ", vec.x, " and vec.y = ", vec.y);
}

---

Minor tweaks might be necessary, but that should get you started.

Reply via email to