其他分享
首页 > 其他分享> > d编译时闭包

d编译时闭包

作者:互联网

//https://forum.dlang.org/post/sopoeb$1098$1@digitalmars.com
import std.stdio, std.traits, core.lifetime;

struct CtDelegate(R,T...){
    void* ctx;
    R function(T,void*) fp;
    R delegate(T) get(){
        R delegate(T) dg;
        dg.ptr=ctx;
        dg.funcptr=cast(typeof(dg.funcptr))fp;
        return dg;
    }
    alias get this;
    this(void* ctx,R function(T,void*) fp){ this.ctx=ctx; this.fp=fp; }
    R opCall(T args){ return fp(args,ctx); }
}

auto makeCtDelegate(alias f,C)(C ctx){
    static struct Ctx{ C ctx; }
    return CtDelegate!(ReturnType!(typeof(f)),ParameterTypeTuple!f[0..$-1])(new Ctx(forward!ctx),
          (ParameterTypeTuple!f[0..$-1] args,void* ctx){ auto r=cast(Ctx*)ctx; return f(r.ctx,forward!args); });
}

struct A{
    CtDelegate!void[] dg;
}

auto createDelegate(string s){
    return makeCtDelegate!((string s){ s.writeln; })(s);
}

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


void main(){
    static a = create();
    foreach(dg; a.dg)dg();
}
//另一版本:
interface ICallable
{
    void opCall() const;
}

auto makeDelegate(alias fun, Args...)(auto ref Args args)
{
    return new class(args) ICallable
    {
        Args m_args;
        this(Args p_args) { m_args = p_args; }
        void opCall() const { fun(m_args); }
    };
}

alias Action = void delegate();

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

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();
}

标签:fp,return,dg,void,args,ctx,时闭,编译
来源: https://blog.csdn.net/fqbqrr/article/details/121798967