【发布时间】:2020-05-22 08:53:43
【问题描述】:
我想将MachineT 中的所有States 实例化为shared_ptr<T>,然后通过类型名访问它们。
在下面的代码中,它指的是实例化(MachineT 构造函数)和访问状态的方法(get 函数)。
是否有任何 hashmap 技巧或方法可以在类中存储“索引”信息,例如 StateA::Index?
#include <memory>
#include <vector>
template <typename... States>
class MachineT {
public:
MachineT() {
states_.resize(sizeof...(States));
for (unsigned i = 0; i < states_.size(); ++i) {
// Instanciate states
// states_[i].reset(new decltype(State[i])());
}
}
~MachineT() {}
class State {
State(int state_id) : state_id_(state_id) {}
const size_t state_id_;
};
template<typename T>
std::shared_ptr<T> get() {
// Retrun the shared_ptr to the State
}
std::vector<std::shared_ptr<State>> states_;
};
struct StateA; // Forward declaration
struct StateB;
using StateMachine = MachineT<StateA, StateB>;
class StateA : StateMachine::State {};
class StateB : StateMachine::State {};
int main(int argc, char const* argv[]) {
StateMachine sm;
std::shared_ptr<StateA> state_a = sm.get<StateA>();
return 0;
}
【问题讨论】:
标签: c++ c++14 template-meta-programming parameter-pack