Created
December 23, 2013 02:01
-
-
Save bithavoc/8090819 to your computer and use it in GitHub Desktop.
EventList implementation in D with syntax sugar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import std.stdio; | |
| import std.algorithm; | |
| import std.string; | |
| // event list declared with string return value, first parameter as string and second parameters as int. | |
| static EventList!(string, string, int) formatter; | |
| // event list declared with no parameters and returning void. | |
| static EventList!void voidEvents; | |
| void main() { | |
| auto a = 2; | |
| formatter = new EventList!(string, string, int)(); | |
| // add a delegate to the list | |
| formatter.add((text, value){ | |
| a++; | |
| return text.format(value); | |
| }); | |
| // same operation but with ^ | |
| formatter ^ (text, value) { | |
| return "replaced by last call"; | |
| }; | |
| auto text = formatter.execute("hello %d", 23); | |
| text.writeln; | |
| voidEvents = new EventList!void; | |
| voidEvents ^ { | |
| "simple to execute".writeln; | |
| }; | |
| voidEvents.execute; | |
| } | |
| class EventList(TReturn, Args...) { | |
| TReturn delegate(Args)[] _list; | |
| auto opBinary(string op)(TReturn delegate(Args) rhs) { | |
| static if (op == "^") { | |
| this.add(rhs); | |
| } | |
| else static assert(0, "Operator "~op~" not implemented"); | |
| return this; | |
| } | |
| public: | |
| void add(TReturn delegate(Args args) d) { | |
| _list ~= d; | |
| writeln("added event, count is", _list.length); | |
| } | |
| auto execute(Args args) { | |
| static if (is( TReturn == void )) { | |
| // it's void returning, don't do anything | |
| foreach(d;_list) { | |
| d(args); | |
| } | |
| } else { | |
| // execute saving the last result | |
| TReturn v; | |
| foreach(d;_list) { | |
| v = d(args); | |
| } | |
| return v; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment