Properties don't work as expected

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 6 13:09:08 PDT 2016


On Wednesday, 6 July 2016 at 10:25:44 UTC, zodd wrote:
> Thank you for a great example! D's power still surprises me a 
> lot.

just be careful to not carry wrapper around for too long, so it 
won't outlive it's parent.

p.s. or this (abomination, i know!). ripped out of one of my 
monkeycoding projects:


import std.stdio;

template GST(string fldname, size_t l=__LINE__) {
   private import std.conv : to;
   private enum bgsn = "z_buildGST_"~l.to!string;
   private enum gn = "get_"~fldname;
   private enum sn = "set_"~fldname;
   private enum ft = "typeof(cast()"~gn~")";
   enum GST =
     "private alias "~bgsn~"_T = "~ft~";"~
     "public @property auto "~fldname~"() (in auto ref "~bgsn~"_T 
v) { "~sn~"(v); return "~bgsn~"; }\n"~
     "public @property auto "~fldname~"() () const { return 
"~gn~"; }\n"~
     "public @property auto "~fldname~"() () { return "~bgsn~"; 
}\n"~
     "private auto "~bgsn~"(T=typeof(this)) () {\n"~
     "  static struct "~bgsn~"_st {\n"~
     "    T* _p;\n"~
     "    alias _g this;\n"~
     "    auto _g () inout { return _p."~gn~"; }\n"~
     "    ref auto opAssign() (in auto ref "~bgsn~"_T v) { 
_p."~sn~"(v); return this; }\n"~
     "    ref auto opOpAssign(string op) (in auto ref "~bgsn~"_T 
v) { _p."~sn~"(mixin(`_p."~gn~"`~op~`v`)); return this; }\n"~
     "    string toString () const { import std.conv : to; return 
_p."~gn~".to!string; }\n"~
     "  }\n"~
     "  return "~bgsn~"_st(&this);\n"~
     "}\n"~
     "";
}

struct Foo {
   int mVal;

   this (int n) { mVal = n; }

   int get_val () const {
     //import core.stdc.stdio : printf; printf("getter\n");
     return mVal+1000;
   }

   void set_val (int v) {
     //import core.stdc.stdio : printf; printf("setter\n");
     mVal = v%1000;
   }

   mixin(GST!"val");
}


void main () {
   writeln(Foo(42).val = 45);

   Foo foo;
   foo.val = 1020;
   writeln("mv: ", foo.mVal, " : ", foo.val);

   foo.val += 15;
   writeln("mv: ", foo.mVal, " : ", foo.val);

   foo.val--;
   writeln("mv: ", foo.mVal, " : ", foo.val);

   int n = (foo.val += 6);
   writeln("n: ", n);
   writeln("mv: ", foo.mVal, " : ", foo.val);
}


More information about the Digitalmars-d-learn mailing list