2

我对这个有点难过。考虑它的最简单方法是一组实现状态机状态并返回下一个状态的函数(请注意 - FSM 示例只是激励性的,我不是在寻找如何设计 FSM)。

所以我正在寻找 C 风格的 typedef 和 C++ 11 使用 StateHandler (函数指针)的定义,其中代码类似于(忽略声明等......):

// typdef for StateHandler
// -- and to see the new c++ 11 way --
// using StateHandler = StateHandler (*)(State *, int);  // note -- does not compile

StateHandler StateOne(State *state, int arbitraryArgs) {
    // do stuff and go to state 2
    return StateTwo;
}

StateHandler StateTwo(State *state, int arbitraryArgs) {
     // do stuff and go to state 1
    return StateOne;
}
4

2 回答 2

2

You cannot do this as it would require the infinite type. You need to use function objects here.

struct StateOne;
struct StateTwo;

struct StateOne {
    StateTwo operator()(State* state, int arbitraryArgs) const;
};

struct StateTwo {
    StateOne operator()(State* state, int arbitraryArgs) const;
};

StateTwo StateOne::operator()(State* state, int arbitraryArgs) const {
    // do stuff
    return StateTwo();
}

StateOne StateTwo::operator()(State* state, int arbitraryArgs) const {
    // do stuff
    return StateOne();
}

If you want a variable that can store either of these function objects, you need type erasure. You can do this with an abstract base class that contains a pure virtual operator() function, and std::unique_ptr.

于 2013-11-10T16:35:16.773 回答
1

函数类型的名称在哪里FuncType,不能让它返回FuncType。但是您可以让它返回一个围绕函数类型 ( StateHandler) 的轻量级包装器。然后我们可以定义函数调用操作符operator(),让 this 表现得像一个函数。

struct StateHandler;

typedef StateHandler (*FuncType)(State *, int); //using FuncType = StateHandler (*)(State *, int);

struct StateHandler {
        FuncType m_f;
        StateHandler(FuncType f_) : m_f(f_) {}
        StateHandler operator() (State *s, int arbitraryArgs) {
                return m_f(s,arbitraryArgs);
        }
};

// declare both functions in advance, so their definitions can return each other
StateHandler StateOne(State *state, int arbitraryArgs);
StateHandler StateTwo(State *state, int arbitraryArgs);

StateHandler StateOne(State *state, int arbitraryArgs) {
    // do stuff and go to state 2
    return StateTwo;
}

StateHandler StateTwo(State *state, int arbitraryArgs) {
     // do stuff and go to state 1
    return StateTwo;
}
于 2013-11-10T17:53:39.577 回答