[英]Access class implementation instanciated from template parameter packs
I would like to instantiate all States
in the MachineT
as a shared_ptr<T>
then access them by typename.我想将
MachineT
中的所有States
实例化为shared_ptr<T>
然后通过类型名访问它们。
In the following code, it refers to the instantiation (MachineT constructor) and a way to access the states (get function).在下面的代码中,它指的是实例化(MachineT 构造函数)和访问状态的方法(get 函数)。
Is there any hashmap trick or a way to store in the class an "Index" information such as StateA::Index
?是否有任何 hashmap 技巧或方法可以在 class 中存储“索引”信息,例如
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;
}
It's perfectly doable.这是完全可行的。 Here's how to do it in C++14:
以下是在 C++14 中的操作方法:
#include <memory>
#include <tuple>
template <typename... States>
class MachineT {
public:
MachineT()
: states_{
std::make_shared<States>()...
} {
}
~MachineT() {}
template<typename T>
std::shared_ptr<T> get() {
return std::get<std::shared_ptr<T>>(states_);
}
std::tuple<std::shared_ptr<States>...> states_;
};
struct State1 {};
int main() {
MachineT<State1> a;
a.get<State1>();
}
Equivalent of std::get
can be implemented with C++11 tools可以使用 C++11 工具实现等效的
std::get
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.