Wrapper Struct

Salih Dincer salihdb at hotmail.com
Wed Dec 21 07:25:50 UTC 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():

```d
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():

```d
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 at 79


More information about the Digitalmars-d mailing list