Thread overview
Wrapper Struct
Dec 21, 2022
Salih Dincer
Dec 21, 2022
rikki cattermole
Dec 23, 2022
Salih Dincer
December 21, 2022

I want to have a wrapper structure for the variables I want to protect, but in D I can't do it the way I want. It doesn't work in W1 Test's constructor, but it works in main():

struct W1(T) {
  private T value;

  alias getset this;

  @property T getset(T v)
  {
    return value = v;
  }

  @property T getset() inout
  {
    return value;
  }
}

struct W1test {
  W1!int i;

  this(int i) {
    this.i = i;/* doesn't work
    this.i.getset = i; //*/
  }
}

void main()
 {
  import std.stdio;

  W1!int w1;
  w1 = 1;
  w1.writeln;

  auto w1Test = W1test(2);
  w1Test.writeln;
}

What do I do when this doesn't work the way I want! I need to upgrade to a new version (W2) which I did with opCall():

struct W2(T) {
  private T value;

  alias opCall this;

  @property T opCall(T v)
  {
    return value = v;
  }

  @property T opCall() inout
  {
    return value;
  }
}

struct W2test {
  W2!int i;

  this(int i) {
    //this.i = i;/* doesn't work
    this.i(i); //*/
  }
}

void main()
 {
  import std.stdio;

  W2!int w2;
  w2 = 2;
  w2.writeln;

  auto w2Test = W2test(3);
  w2Test.writeln;
}

Yes except one thing, I don't need to know getset() now and everything is as I want:

Why do I need to use parentheses when inside the constructor? Because when I'm in main() I can use it like a regular variable!

SDB@79

December 22, 2022
This may be what you want: https://dlang.org/phobos/std_typecons.html#Proxy
December 23, 2022

On Wednesday, 21 December 2022 at 15:02:42 UTC, rikki cattermole wrote:

>

This may be what you want: https://dlang.org/phobos/std_typecons.html#Proxy

Thank you, now no need proxy! It's works:

void main()
{
  import std.stdio;

  auto p1 = Point(1, 2);
  auto p2 = Point(10, 20);
  writeln(p1 + p2);

  class Foo
  {
    NP!Point point;
    this(double x = 0.0, double y = 0.0)
    {
      point = Point(x, y);
    }
  }

  auto foo = new Foo(0.1234, 567.89);
  writeln(foo.point + p2);
}

struct NP(T) { // NP: No Proxy
  private T value;
  this(T x)
  {
    value = x;
  }

  alias opCall this;
  @property opCall() inout
  {
    return value;
  }

  @property opCall(T x)
  {
    return value = x;
  }
}

struct Point
{
  double x, y;
  pure const nothrow @safe:

  auto opBinary(string op)(in Point rhs) @nogc
  {
    return Point(mixin("x" ~ op ~ "rhs.x"),
                 mixin("y" ~ op ~ "rhs.y"));
  }

  auto opBinary(string op)(int rhs) @nogc
  {
    return Point(mixin("x" ~ op ~ "rhs"),
                 mixin("y" ~ op ~ "rhs"));
  }
}