问题
I'd like to have a class with member functions that return pointers to member functions.
That is, something like:
class Foo {
// typedef ????(Foo::* func)????
public:
Func s1();
Func s2();
Func s3();
}
Func Foo::s1() {
// do stuff
return &Foo::s2;
}
Func Foo::s2() {
// do stuff
return &Foo::s3;
}
Func Foo::s3() {
// do stuff
return 0;
}
Basically, what I try to do is to implement a state machine, where each state nows the next state and returns it by means of a function pointer.
Note: I'm not interested in other ways of implementing a state machine. I really like to know if it can be implemented in a way that looks like the above.
Context: I got inspired by this talk: http://www.youtube.com/watch?v=HxaD_trXwRE and wondered if a similar pattern can be used in C++.
回答1:
Blatently ripping off the solution at GotW and adapting it to member functions:
class Foo {
public:
struct FuncPtrRet;
typedef FuncPtrRet(Foo::*FuncPtr)();
struct FuncPtrRet {
FuncPtrRet(FuncPtr pp) : p(pp) { }
operator FuncPtr() { return p; }
FuncPtr p;
};
FuncPtrRet s1() { return &Foo::s2; }
FuncPtrRet s2() { return &Foo::s3; }
FuncPtrRet s3() { return &Foo::s3; }
};
int main() {
Foo test;
Foo::FuncPtr state = test.s1();
state = (test.*state)();
state = (test.*state)();
state = (test.*state)();
state = (test.*state)();
state = (test.*state)();
return 0;
}
This seems to work on Clang 3.3. I don't think returning 0 is a good choice for an idle state (s3 here), but I might be wrong there. Having an idle state that returns itself seems more intuitive to me.
来源:https://stackoverflow.com/questions/19600044/member-functions-returning-pointers-to-member-functions