【问题标题】:Access class implementation instanciated from template parameter packs从模板参数包实例化的访问类实现
【发布时间】: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


    【解决方案1】:

    这是完全可行的。以下是在 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>();
    }
    

    std::get 的等价物可以用 C++11 工具实现

    【讨论】:

    • Inheritance 和 MachineT::State 似乎不再需要(我认为 OP 使用该技巧为容器提供通用类型)。
    • std::get&lt;T&gt; 是 C++14,而问题被标记为 C++11(可能错误的标签作为答案被接受;))
    • 嗯,我在评论那。应该提到这是一个 C++14 解决方案。我将添加 C++14 标志以防止混淆。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多