【问题标题】:Return function pointer to function that returns the same type [duplicate]返回指向返回相同类型的函数的函数指针[重复]
【发布时间】:2014-03-17 19:31:11
【问题描述】:

在 C 中,我如何声明一个返回函数的函数,该函数返回一个函数等。 即,我想要这样的东西

typedef A (*A)();
A a = ...
a()()()()();

我想实现以下 C++ 行为:

struct A { A operator()() { return A(); } };
A a;
a()()()()();

【问题讨论】:

  • 之前在 SO 上看到过这个,但是找不到了,但是我认为答案是在 C 中是不可能的。
  • @chux typedef int (*f)(int); typedef f (*g)(int); typedef g (*h)(int); 等等怎么样。
  • @ajay 我误解了 OP 的帖子。我认为OP希望函数返回与函数相同的类型。也许不是?
  • @chux:我也是这么想的。我也见过。
  • 和 ajay 的例子一样,在 C 中你返回的是函数的指针,而不是函数。

标签: c function-pointers


【解决方案1】:

你不能在C 中返回一个函数——你返回一个指向函数的指针。如果您的意思是定义一个返回指向函数的指针的函数,该函数再次返回指向函数的指针等等,那么您可以使用typedef 来实现它。

typedef int (*f)(int);
typedef f (*g)(float);
typedef g (*h)(char);

// and so on

但是,如果您要定义一个返回指向其自身类型函数的指针的函数,那么您不能这样做,因为您不能在C 中定义递归类型。详情见这里 - Function Returning Itself

【讨论】:

    【解决方案2】:

    答案是“几乎是的”。

    看看 Drew McGowen 回复 Function Returning Itself 时给出的答案。

    我认为该答案提供的代码最接近您试图看到的行为。

    【讨论】:

      【解决方案3】:

      要让函数返回其自身类型的函数,需要使用中间函数类型。

      根据 C 标准,允许将函数变量转换为任何其他函数变量并返回以下方法:

      typedef int (*T)(void); /* The type of desire. */
      typedef void (*_T)(void);  /* The intermediate type. */
      
      int g(void)
      {
        return 42;
      }
      
      _T h(void)
      {
        return (_T) g;
      }
      
      int main(void)
      {
        T f = (T) h;
        int a = f();
        int b = ((T) h())();
      }
      

      ab 都得到 42assigned。

      【讨论】:

      • 这不是问题所在。你从来没有定义一个返回自身的函数——h() 返回一个指针,指向一个什么也不接收也不返回的函数——它确实 not 返回自己。这在 C 中是不可能的,类型系统不允许这样做。当然,您可以使用指针和强制转换来模拟这种行为,但从技术上讲,这不是 OP 想要的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多