Typedeffing a function (NOT a function pointer)

前端 未结 6 2239
醉酒成梦
醉酒成梦 2020-12-17 05:20
typedef void int_void(int);

int_void is a function taking an integer and returning nothing.

My question is: can it be

相关标签:
6条回答
  • 2020-12-17 05:39

    It can be used in the following cases (out of the top of my head):

    • generic code:

      boost::function<int_void> func;

    • other typedefs:

      typedef int_void* int_void_ptr;

    • declarations:

      void add_callback(int_void* callback);

    There may be others.

    0 讨论(0)
  • 2020-12-17 05:46

    I think it's legal - the following demonstrates its use:

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

    and actually, this C++ code compiles (with g++) & runs - I'm really not sure how kosher it is though.

    #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);
    }
    
    0 讨论(0)
  • 2020-12-17 05:49

    What happens is that you get a shorter declaration for functions.

    You can call test, but you will need an actual test() function.

    You cannot assign anything to test because it is a label, essentially a constant value.

    You can also use int_void to define a function pointer as Neil shows.


    Example

    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)
    {
    }
    
    0 讨论(0)
  • 2020-12-17 05:54

    You are not declaring a variable; you are making a forward declaration of a function.

    typedef void int_void(int);
    int_void test;
    

    is equivalent to

    void test(int);
    
    0 讨论(0)
  • 2020-12-17 06:00

    This should work, no casting required:

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

    A function's name "devolves" into a function pointer anytime you use the function's name in something other than a function call. If is is being assigned to a func ptr of the same type, you don't need a cast.

    The original

    typedef int_void(int);
    

    is not useful by itself, without using a pointer to the type. So the answer to your question is "no, you can't use that typedef without a pointer".

    0 讨论(0)
  • 2020-12-17 06:01

    Pointers to functions are values in C/C++. Functions are not.

    0 讨论(0)
提交回复
热议问题