d指向结构的方法

原文
如何"提取"并使用闭包中的函数指针?

struct S {
   void function () fp;
   void foo ()
   {
      fp = (&bar).funcptr;
   }
   void bar ()
   {
      fp = (&foo).funcptr;
   }
   auto fun () // 帮助函数
   {
      if (! fp)
         fp = (&foo).funcptr;
      void delegate () dg;
      dg.ptr = &this;
      dg.funcptr = fp;
      return dg ();
   }
}

unittest {
   S s;
   s.fun;
   s.fun;
}

d作者建议用λ:

struct S {
   :
   void function (ref S) fp;
   :
   void foo () {
      :
      fun = function (ref S self) { return self.bar (); };
      :
   }
   :
}

可以这样:

template funcptr (alias method) {
   enum funcptr = &method;
}

ldc来证明一致性.以下每一项都可防止重新赋值函数地址:

immutable string function() f = &S.bar;
  const string function() f = &S.bar;
  enum f = &S.bar;

相反,以下没有这样限制:

string function() f = &S.bar;
//示例:

  struct S {
    string bar(){return "Hello";}
    string foo(){return "Goodbye";}
  }

  void main() {
    string function() f = &S.bar;
    writeln(f, " ", f());
    f = &S.foo;
    writeln(f, " ", f());
  }
posted @ 2022-10-16 10:17  zjh6  阅读(20)  评论(0)    收藏  举报  来源