c++ - 为函数定义 typedef,该函数返回指向与其自身类似的函数的函数指针

标签 c++ c pointers

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

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

// 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;
}

最佳答案

您不能这样做,因为它需要无限类型。您需要在这里使用函数对象。

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();
}

如果您想要一个可以存储这些函数对象中的任何一个的变量,则需要类型删除。您可以使用包含纯虚拟 operator() 函数和 std::unique_ptr 的抽象基类来完成此操作。

关于c++ - 为函数定义 typedef,该函数返回指向与其自身类似的函数的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19892099/

相关文章:

c++ - 什么时候重载 operator new?

c - 简单的 32 位到 64 位转换?

c - 如何使用 strstr 函数返回值?

c - 指针声明/引用后的方括号

c - 从 32 位地址闪存读取 double 值

c++ - 将字符串传递给 file.open();

c++ - 在 C++11 中使用 boost::hash_value 定义 std::hash

c++ - 更改 vector 值导致段错误

c - 在此函数中未初始化使用

c++ - 看不懂具体的代码片段 : Is this a function, 只是一行还是什么?