【发布时间】:2020-06-17 16:26:41
【问题描述】:
我正在尝试制作一个简单的模板化 FSM 库,该库将允许:machine.react(Event1{}); 它将调用实现 SomeState.react(std::shared_ptr<StateMachine> machine, Event1 event),而无需提前知道所有可能的事件,也无需实现所有可能的事件所有派生类。
当我从存储为State 类型的 current_state_ 中调用函数时,在调用 react(不是虚拟的)时,它将调用 Base 实现而不是 Derived (State1) 类实现。
#include <iostream>
#include <memory>
#include <tuple>
#include <typeinfo>
#include <vector>
template <typename ContextT, typename... StatesT>
class MachineT : public std::enable_shared_from_this<MachineT<ContextT, StatesT...>> {
using M_ = MachineT<ContextT, StatesT...>;
public:
using Context = ContextT;
class State {
public:
template <typename EVENT>
void react(std::shared_ptr<M_> machine, EVENT event) {
std::cout << "State::react" << std::endl;
};
virtual void update(std::shared_ptr<M_> machine) = 0;
};
MachineT(std::shared_ptr<ContextT> context)
: context_(context),
states_{std::make_shared<StatesT>()...} {
using FirstEntityType = std::tuple_element_t<0, std::tuple<StatesT...>>;
set<FirstEntityType>();
}
~MachineT() {}
template <typename T>
std::shared_ptr<T> get() {
return std::get<std::shared_ptr<T>>(states_);
}
template <typename T>
void set() {
current_state_ = std::get<std::shared_ptr<T>>(states_);
}
std::shared_ptr<M_> shared() {
return this->shared_from_this();
}
void update(){
current_state_->update(shared());
};
template <typename EVENT>
void react(EVENT event){
current_state_->react(shared(), event);
};
private:
std::shared_ptr<ContextT> context_;
std::tuple<std::shared_ptr<StatesT>...> states_;
std::shared_ptr<State> current_state_;
};
struct State1;
struct State2;
struct Context {};
struct Event1 {};
using StateMachine = MachineT<Context, State1, State2>;
struct State1 : public StateMachine::State {
int value = 10;
void print() { std::cout << value << std::endl; }
void react(std::shared_ptr<StateMachine> machine, Event1 event) {
std::cout << "State1::react()" << std::endl;
}
void update(std::shared_ptr<StateMachine> machine) {
std::cout << "State1::update()" << std::endl;
}
};
struct State2 : public StateMachine::State {
int value = 20;
void print() { std::cout << value << std::endl; }
void react(std::shared_ptr<StateMachine> machine, Event1 event) {
std::cout << "State2::react()" << std::endl;
}
void update(std::shared_ptr<StateMachine> machine) {
std::cout << "State2::update()" << std::endl;
}
};
int main() {
std::shared_ptr<Context> context;
context.reset(new Context());
std::shared_ptr<StateMachine> machine;
machine.reset(new StateMachine(context));
machine->set<State1>();
machine->update();
machine->react(Event1{});
machine->set<State2>();
machine->update();
machine->react(Event1{});
}
完整示例:http://cpp.sh/7d37rq
当前输出:
State1::update()
State::react()
State2::update()
State::react()
预期输出:
State1::update()
State1::react()
State2::update()
State2::react()
【问题讨论】:
-
[OT]:有了injected class name,可以去掉
M_,直接使用MachineT。 -
那么您希望非虚拟函数如何做到这一点?为什么您希望您的州能够对过去、现在和未来的每一种可能的事件类型做出反应?在我的书中,状态机由一组固定的状态和一组固定的事件和一个转换矩阵定义。..