How to create a function that returns a functor with the same signature as the function?

Is it possible in C ++ to create a function that returns a functor with the same signature as the function?

basically how to legalize decltype(foo) foo(); .

or with functors: function<function<function<...(void)>(void)>(void)>

I would like to use this for a state machine, where each state is a function that returns a functor to the next state of the object. I have now implemented it with enumerations, but I feel that there should be a better way:

 #include <iostream> using namespace std; enum functionenum{END,FOO,BAR,BAZ}; functionenum foo(){ cout<<"FOO! > "; string s; cin>>s; if(s=="end") return END; if(s=="bar") return BAR; return FOO; } functionenum bar(){ cout<<"BAR! > "; string s; cin>>s; if(s=="end") return END; if(s=="baz") return BAZ; return BAR; } functionenum baz(){ cout<<"BAZ! > "; string s; cin>>s; if(s=="end") return END; if(s=="bar") return BAR; if(s=="foo") return FOO; return BAZ; } void state(){ auto f=foo; while(true){ switch (f()){ case FOO: f=foo; break; case BAR: f=bar; break; case BAZ: f=baz; break; case END: return; }; }; } int main(){ state(); } 

also: is there a less awkward way to pose the question?

+7
source share
1 answer

You can break type recursion by wrapping a function in a struct:

 #include <string> struct state { typedef state (*state_func)( const std::string &); state( state_func f): function(f){} //not explicit, for notational convenience state operator()( const std::string&arg) const { return function( arg); } private: state_func function; }; state f( const std::string &); state g( const std::string &) { return &f; } state f( const std::string &) { return &g; } int main() { state s(&f); s = s( "hello"); return 0; } 

UPDATE: after comments from Yakk ("make it more general") and Luke Danton ("Classic GOTW ") I have added a more general version of C ++ 11 below, based on the GOTW version.

 /// Type that wraps functions that return functions with the same signature. template<typename... Arguments> struct SelfReturningFunction { typedef SelfReturningFunction (*FunctionPointer)( Arguments...); SelfReturningFunction( FunctionPointer f): function(f){} operator FunctionPointer() const { return function; } private: FunctionPointer function; }; // example usage #include <string> using state = SelfReturningFunction<const std::string&>; state f( const std::string &); state g( const std::string &) { return &f; } state f( const std::string &) { return &g; } state dead_end( const std::string &) { return &dead_end; } int main() { state s{&f}; s = s( "hello"); return 0; } 
+7
source

All Articles