代码之家  ›  专栏  ›  技术社区  ›  Andreas Bonini

typedefing函数(不是函数指针)

  •  4
  • Andreas Bonini  · 技术社区  · 16 年前
    typedef void int_void(int);
    

    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;
    
    6 回复  |  直到 16 年前
        1
  •  7
  •   jbcreix    16 年前

    结果是您得到了一个较短的函数声明。

    你可以打电话 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)
    {
    }
    
        2
  •  3
  •   Jim Buck    16 年前

    您没有声明变量;您正在对函数进行正向声明。

    typedef void int_void(int);
    int_void test;
    

    等于

    void test(int);
    
        3
  •  2
  •   utnapistim    16 年前

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

    • 通用代码:

      boost::函数<int_void>func;

    • 其他类型:

      typedef int_void*int_void_ptr;

    • 声明:

      void add_回调(int_void*回调);

    可能还有其他的。

        4
  •  1
  •   anon    16 年前

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

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

    事实上,这个C++代码编译(用g++)和运行-我真的不知道它是如何犹太的。

    #include <stdio.h>
    
    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);
    }
    
        5
  •  0
  •   yfeldblum    16 年前

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

        6
  •  -1
  •   Tim Schaeffer    16 年前

    这应该有效,不需要铸造:

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

    每当您在函数调用之外的其他地方使用函数的名称时,函数的名称“转为”函数指针。如果是分配给同一类型的func ptr,则不需要强制转换。

    原文

    typedef int_void(int);
    

    如果不使用指向类型的指针,则本身就不有用。所以问题的答案是“不,没有指针就不能使用typedef”。