How to make a function return a pointer to a function? (C++)

Solution 1:

int f(char) {
    return 0;
}

int (*return_f())(char) {
    return f;
}

No, seriously, use a typedef :)

Solution 2:

#include <iostream>
using namespace std;

int f1() {
    return 1;
}

int f2() {
    return 2;
}

typedef int (*fptr)();


fptr f( char c ) {
    if ( c == '1' ) {
        return f1;
    }
    else {
        return f2;
    }
}

int main() {
    char c = '1';
    fptr fp = f( c );
    cout << fp() << endl;
}

Solution 3:

Create a typedef for the function signature:

typedef void (* FuncSig)(int param);

Then declare your function as returning FuncSig:

FuncSig GetFunction();

Solution 4:

Assuming int f(char) and ret_f which returns &f.

C++98/C++03 compatible ways:

  • Ugly way:

    int (*ret_f()) (char) { return &f; }
    
  • With typedef:

    typedef int (sig)(char);
    
    sig* ret_f() { return &f; }
    

    or:

    typedef int (*sig_ptr)(char);
    
    sig_ptr ret_f() { return &f; }
    

Since C++11, in addition we have:

  • with decltype:

    decltype(&f) ret_f() { return &f; }
    
  • trailing return type:

    auto ret_f() -> int(*)(char) { return &f; }
    

    or:

    auto ret_f() -> decltype(&f) { return &f; }
    
  • typedef with using:

    using sig = int(char);
    
    sig* ret_f() { return &f; }
    

    or:

    using sig_ptr = int (*)(char);
    
    sig_ptr ret_f() { return &f; }
    

C++14 adds:

  • auto deduction:

    auto ret_f() { return &f; }