如何定义一个可以返回指向自身的指针的函数?

发布于 2024-09-07 22:19:11 字数 208 浏览 2 评论 0原文

我想编写这样的代码:

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

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

是否可以以完全类型安全的方式做到这一点?假设使用 C、C++、D、C#、Java 或任何其他静态类型语言。

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 statically typed language.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

智商已欠费 2024-09-14 22:19:11

这是一个 C# 示例

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

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;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文