Adding syntacti sugar for simple "readonly" attribute ?

jmh530 john.michael.hall at gmail.com
Thu Oct 26 22:11:53 UTC 2017


On Thursday, 26 October 2017 at 21:19:28 UTC, LunaticWare wrote:
> [snip]

You can use string mixins.

template GenGetterSetter(string Type, string Name)
{
     const char[] GenGetterSetter = "    private " ~ Type ~ " " ~ 
Name ~ "_;\n" ~
                                    "    this(" ~ Type ~ " x)\n" ~
                                    "    {\n" ~
                                    "        " ~ Name ~ "_ = x;\n" 
~
                                    "    }\n" ~
                                    "    @property " ~ Type ~ " " 
~ Name ~ "()\n" ~
                                    "    {\n" ~
                                    "        return " ~ Name ~ 
"_;\n" ~
                                    "    }";
}

class Foo
{
     mixin(GenGetterSetter!("string", "bar"));
}

void main()
{
     import std.stdio : writeln;
     Foo foo = new Foo("bar");
     writeln(foo.bar);
}


More information about the Digitalmars-d mailing list