Typedeffing一个函数(不是函数指针)

typedef void int_void(int); 

int_void是一个取整数并且不返回任何内容的函数。

我的问题是: 它可以“单独”使用,没有指针吗? 也就是说,是否可以将其用作简单的int_void而不是int_void*

 typedef void int_void(int); int_void test; 

这段代码编译。 但是可以test某种方式使用或分配给某些东西(没有演员表)?


 /* Even this does not work (error: assignment of function) */ typedef void int_void(int); int_void test, test2; test = test2; 

会发生什么,你得到一个较短的函数声明。

您可以调用test ,但是您需要一个实际的test()函数。

您无法指定任何要测试的内容,因为它是一个标签,实际上是一个常量值。

你也可以使用int_void来定义Neil所显示的函数指针。


 typedef void int_void(int); int main() { int_void test; /* Forward declaration of test, equivalent to: * void test(int); */ test(5); } void test(int abc) { } 

你没有声明变量; 你正在做一个函数的前向声明。

 typedef void int_void(int); int_void test; 

相当于

 void test(int); 

它可用于以下情况(我的头顶):

  • 通用代码:

    boost :: function func;

  • 其他typedef:

    typedef int_void * int_void_ptr;

  • 声明:

    void add_callback(int_void * callback);

可能还有其他人。

我认为这是合法的 – 以下说明了它的用途:

 typedef void f(int); void t( int a ) { } int main() { f * p = t; p(1); // call t(1) } 

实际上,这个C ++代码编译(使用g ++)并运行 – 我真的不确定它是多么犹豫不决。

 #include  typedef void f(int); void t( int a ) { printf( "val is %d\n", a ); } int main() { f & p = t; // note reference not pointer p(1); } 

函数指针是C / C ++中的值。 function不是。

这应该工作,不需要铸造:

 void f(int x) { printf("%d\n", x); } int main(int argc, const char ** argv) { typedef void (*int_void)(int); int_void test = f; ... } 

只要在函数调用以外的函数中使用函数的名称,函数的名称就会“转换”为函数指针。 如果is被分配给相同类型的func ptr,则不需要强制转换。

原本的

 typedef int_void(int); 

如果没有使用指向该类型的指针,它本身就没用。 所以问题的答案是“不,你不能在没有指针的情况下使用那个typedef”。