D的部分应用

import std.stdio, std.traits, core.lifetime;
auto partiallyApply(alias fun,C...)(C context){
    return &new class(move(context)){
        C context;
        this(C context) { foreach(i,ref c;this.context) c=move(context[i]); }
        auto opCall(ParameterTypeTuple!fun[context.length..$] args) {
            return fun(context,forward!args);
        }
    }.opCall;
}

alias Action = void delegate();

Action createDelegate(string s){
    import std.stdio;
    return partiallyApply!((string str) => writeln(str))(s);
}

struct A{ Action[] dg; }

A create(){
    A a;
    a.dg ~= createDelegate("hello");
    a.dg ~= createDelegate("buy");
    return a;
}

void main(){
    enum a = create();
    foreach(dg; a.dg)
        dg();
}
posted @ 2021-12-09 10:29  zjh6  阅读(22)  评论(0)    收藏  举报  来源