开发者

How to define a function that can return a pointer to itself?

I want to write code like this:

/*something*/ Fn() { ... }

int main()
{
  /*something*/ fn = Fn;
  while(fn) fn = fn();
  return 0;
}

Is it possible to do this is a fully type safe way? Assume C, C++, D, C#, Java, or any other staticall开发者_开发问答y typed language.


Here is a C# example

delegate MyFunctionDelegate MyFunctionDelegate();

class Program
{
    static void Main(string[] args)
    {
        MyFunctionDelegate fn = FN1;
        while (fn!=null)
            fn = fn();
    }

    static MyFunctionDelegate FN1()
    {
        Console.WriteLine("FN1 called");
        MyFunctionDelegate returnDelegate = FN2;
        return returnDelegate;
    }

    static MyFunctionDelegate FN2()
    {
        Console.WriteLine("FN2 called");
        return null;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜