+ 2

Can you return a function in C++?

I know that you can pass functions as arguments through function pointers. Is it also possible to use those function pointers to make a function return another function?

2nd May 2019, 6:00 AM
Kulisap
Kulisap - avatar
3 Antworten
+ 6
Seems to be possible. I found this on Stackoverflow: #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; }
2nd May 2019, 6:08 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 5
Alternatively, you can use std::function from <functional> which provides a wrapper over function pointers for storing and operating on functions. en.cppreference.com/w/cpp/utility/functional/function Using std::function, you can perform assignments and other operations on functions as if they were normal types like int or char. std::function objects can hold lambdas and functors as well. https://code.sololearn.com/cwB1e1M1N591/?ref=app The code can be easily modified for operating on generic functions. https://code.sololearn.com/cQkRHFve9syw/?ref=app
2nd May 2019, 6:52 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 4
I found another answer where you can use the keyword "using" instead of "typedef": https://www.sololearn.com/Discuss/1813394/?ref=app
26th May 2019, 3:28 PM
Kulisap
Kulisap - avatar