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?
Douwe van gijn
source share