Returning function pointer type

前端 未结 7 1929
心在旅途
心在旅途 2020-11-29 20:08

Often I find the need to write functions which return function pointers. Whenever I do, the basic format I use is:

typedef int (*function_type)(int,int);

fu         


        
相关标签:
7条回答
  • 2020-11-29 20:12
    int (*getFunc())(int, int) { … }
    

    That provides the declaration you requested. Additionally, as ola1olsson notes, it would be good to insert void:

    int (*getFunc(void))(int, int) { … }
    

    This says that getFunc may not take any parameters, which can help avoid errors such as somebody inadvertently writing getFunc(x, y) instead of getFunc()(x, y).

    0 讨论(0)
  • 2020-11-29 20:19

    You can write the following code(It only works in C++11 and above):

    //C++11
    auto func(...) {
        int (*fptr)(...) ret = ...
        //Do sth.
        return ret;//C++11 compiler will automatically deduce the return type for you
    }
    

    Or, if you do not like automatic return type deduction, you can specified the type at the end of the function(Same as above, only in C++11 and above):

    //C++11
    auto func(...) -> int (*)(...) { /* Do sth. */ }
    
    0 讨论(0)
  • 2020-11-29 20:20

    You can probably do something like:

    int foo (char i) {return i*2;}
    
    int (*return_foo()) (char c)
    {
       return foo;
    }
    

    but god, I hope I'll never have to debug you code....

    0 讨论(0)
  • 2020-11-29 20:29

    I think you've got three options:

    1. Stick with typedef. At the end of the day, it's typedef's job.
    2. Return void* and the casting it.
    3. Reconsider your software architecture. Perhaps you could share with us what you're trying to achieve and see if we can point you toward a better direction.
    0 讨论(0)
  • 2020-11-29 20:30

    This is a stupid example, but it's simple and it does not give errors. It's just about declaring static functions:

    #include <stdio.h>
    #include <stdlib.h>
    
    void * asdf(int);
    static int * hjkl(char,float);
    
    main() {
      int a = 0;
      asdf(a);
     }
    
    
    void * asdf(int a) {return (void *)hjkl; }
    static int * hjkl(char a, float b) {int * c; return c;}
    
    0 讨论(0)
  • 2020-11-29 20:34

    ill leave this here since it was a bit trickier than answers already given, as it takes a function pointer

    (int (__cdecl *)(const char *))

    and returns a function pointer

    (int (__cdecl *)(const char *))

    #include <stdio.h>
    
    int (*idputs(int (*puts)(const char *)))(const char *) {
        return puts;
    }
    
    int main(int argc, char **argv)
    {
        idputs(puts)("Hey!");
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题