Returning function pointer type

前端 未结 7 1921
心在旅途
心在旅途 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:37

    While wrapping some C code in C++ classes, I had the same desire as the original poster: return a function pointer from a function without resorting to typedef'ing the function pointer prototype. I hit a problem with C++ const correctness which I thought was worth sharing, even if it's a little off-topic (C++) but it does relate directly to the original question: the syntax for returning a C function pointer without resorting to a typedef.

    The code below defines a class A which stores a function pointer and exposes it to the outside world through the get_f() call. This is the function that should return a function pointer without a typedef.

    The point (which stumped me for some time) was how to declare that get_f() was a const function, i.e. it wouldn't alter A.

    The code contains 2 variants: the first uses a typedef for the function pointer prototype, whilst the second writes everything out in full. The #if switches between the two.

    #include <iostream>
    
    int my_f(int i)
    {
      return i + 1;
    }
    
    #if 0 // The version using a typedef'ed function pointer
    
    typedef int (*func_t)(int);
    
    class A
    {
    public:
      A(func_t f) : m_f(f) {}
      func_t get_f() const { return m_f; }
    
    private:
      func_t m_f;
    };
    
    int main(int argc, char *argv[])
    {
      const A a(my_f);
      std::cout << "result = " << a.get_f()(2) << std::endl;
    }
    
    #else // The version using explicitly prototyped function pointer    
    
    class A
    {
    public:
      A(int (*f)(int)) : m_f(f) {}
      int (*get_f() const)(int) { return m_f; }
    
    private:
      int (*m_f)(int);
    };
    
    int main(int argc, char *argv[])
    {
      const A a(my_f);
      std::cout << "result = " << a.get_f()(2) << std::endl;
    }
    
    #endif
    

    The expected/desired output is:

    result = 3
    

    The key point is the position of the const qualifier in the line:

    int (*get_f() const)(int) { return m_f; }
    
    0 讨论(0)
提交回复
热议问题