如何在模板参数中调用成员
How to call a member in Template argument?
大家好,我需要使用结构作为派生类和模板参数。在结构内部,有一个名为"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
应该是NodeType
的std::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;
};
相关文章:
- 无法调用成员函数,尝试正确执行此操作仍然失败
- 在 transform() 中调用成员函数
- C++::在构造函数退出之前通过指针调用成员函数
- 为什么我可以通过野生指针调用成员函数
- 从 Qt 中的信号调用成员函数的问题
- 调用C++成员函数指针,而不知道哪个类
- 如何从嵌套在命名空间中的类调用成员函数?
- 无法在非成员函数中调用成员函数
- 为什么分配了 nullptr 的指针可以调用成员函数?
- 通过带有成员函数指针的 QHash 调用成员函数的正确方法
- 使用可变参数模板调用成员函数
- 调用成员对象的构造函数
- 有没有办法在没有括号的情况下在C++中调用成员的getter/setter?
- 如何调用成员初始化器列表中参考成员的构造函数
- 使用按引用调用时,不能在没有对象的情况下调用成员函数 const
- 如果绝对没有调用成员函数,是否允许使用不完整类型的向量?如果是这样,从什么时候开始
- 在另一个成员函数中调用成员函数时'int'之前的预期主表达式
- 为什么调用成员函数不调用该对象的 ODR-USE?
- 如何在模板参数中调用成员
- 是否可以使用 EXPECT_CALL 来验证模拟对象的构造函数是否在某些时候调用成员函数?