Can attributes trigger functionality?

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Sep 5 20:29:35 PDT 2017


On Wednesday, 6 September 2017 at 02:43:20 UTC, Psychological 
Cleanup wrote:
>
> I'm having to create a lot of boiler plate code that creates 
> "events" and corresponding properties(getter and setter).
>
> I'm curious if I can simplify this without a string mixin.


You certainly don't need a string mixin, but you do need some 
code to react to the attribute.

Here's one that generates a wrapper function on-demand:

---

import std.stdio;
import std.traits;

class Test {
         @cool void foo_() {
                 writeln("cool function called");
         }

         mixin CoolFunctions;
}

// our UDA
enum cool;

// adds the decorator implementation
mixin template CoolFunctions() {
         template opDispatch(string name) 
if(hasUDA!(__traits(getMember, typeof(this), name ~ "_"), cool)) {
                 auto opDispatch(Parameters!(__traits(getMember, 
typeof(this), name ~ "_")) params) {
                         writeln("cool before");
                         scope(success) {
                                 writeln("cool after");
                         }
                         return __traits(getMember, this, name ~ 
"_")(params);
                 }
         }
}

void main() {
         auto test = new Test();
         test.foo();
}

-----


No string mixin (uses a mixin template instead), and not even a 
loop over the functions - it does them on-demand when used via 
opDispatch.



More information about the Digitalmars-d-learn mailing list