如何在模板参数中调用成员

How to call a member in Template argument?

本文关键字:调用 成员 参数      更新时间:2023-10-16

大家好,我需要使用结构作为派生类和模板参数。在结构内部,有一个名为"position"的成员。但是,当它用作模板参数时,我找不到如何调用它。有谁知道该怎么做?

struct Node
{
    std::vector<size_t>neighbors;      
};
template<typename NodeType>
class Graph
{
  public:
  void Initialize(size_t nodeCount);
  Node& GetNode(size_t index);
  const Node& GetNode(size_t index)const;
  private:
  std::vector<Node> mNodes;
};
  template<typename NodeType>
  inline void Graph<NodeType>::Initialize(size_t nodeCount)
{
  mNodes.resize(nodeCount);
}
  template<typename NodeType>
  inline Node & Graph<NodeType>::GetNode(size_t index)
{
  return mNodes[index];
}
  template<typename NodeType>
  inline const Node & Graph<NodeType>::GetNode(size_t index) const
{
  return mNodes[index];
}
//Inside the main cpp:
struct MapNode:public Node
{
  X::Math::Vector2 position{ 10.0f,10.0f };
};
 Graph<MapNode> graph;
void BuildGraph()
{
//....
  graph.Initialize(columns * rows);
  for (int r = 0; r < rows; r++)
  {
    for (int c = 0; c < columns; c++)
    {
        int index = c + (r*columns);
        auto& node = graph.GetNode(index);
        // required to call node's position in here
     } 
    // ......
    }
}

首先,Graph类中的mNodes应该是NodeTypestd::vector,而不仅仅是Node。并且该方法GetNode()应该返回一个NodeType而不是一个Node。将类定义为template class但根本不使用模板定义。

template<typename NodeType>
class Graph
{
public:
    void Initialize(size_t nodeCount);
    NodeType& GetNode(size_t index);
    const NodeType& GetNode(size_t index)const;
private:
    std::vector<NodeType> mNodes;
};