On Sunday, 31 May 2020 at 09:37:24 UTC, Ali Çehreli wrote:
On 5/31/20 2:26 AM, Ali Çehreli wrote:

Ok, I solved that too with a very convoluted "eponymous mixin template opDispatch." :)

struct RW(T) {
  template opDispatch(string name) {
    static codeImpl() {
      import std.format;

      return format!q{
        private %s _%s;
        public auto %s() { return _%s; }
        public auto %s(%s val) { _%s = val; return this; }
      }(T.stringof, name,
        name, name,
        name, T.stringof, name);
    }

    mixin template opDispatch(alias code = codeImpl()) {
      mixin (code);
    }
  }
}

struct Point {
  mixin RW!int.x;    // <-- NICE :)
  mixin RW!int.y;
    // etc.
}

import std.traits;
import std.stdio;

void main() {
  pragma(msg, FieldNameTuple!(Point));

  auto p = Point(1, 2);
  p.x = 42;
  p.y = 43;
  writeln(p);
}

Ali


Thank you all for the refinement.

One question: in Sebastiaan's solution opDispatch is performed at run-time, how efficient is the D runtime's implementation of opDispatch compared with a direct regular method call (or a virtual method call in general):
```
public final int x() {return _x;} // in this example it can be final
```

In short, while I want to reduce the boilerplate code I have to write, I don't want to pay any extra run-time cost; compile-time cost is fine.


@Ali in your solution, opDispatch is also performed at run-time instead of compile-time (I'm not sure)? since it's inside struct RW, (each x, y is actually a struct inside Point)?


Reply via email to