[英]How to achieve forward declaration of class template
I am trying to create a Graph
class by using Nested Classes Vertex
and Edge
.我正在尝试使用嵌套类
Vertex
和Edge
创建Graph
class 。 I want to make my Vertex
class to accept generic parameters.我想让我的
Vertex
class 接受通用参数。 I have forward declared my Vertex
class so that I can use it in my Edge
Class.我已经转发声明了我的
Vertex
class,这样我就可以在我的Edge
Class 中使用它。
When I use templates, I get few errors that I am not sure how to resolve.当我使用模板时,我遇到了一些我不确定如何解决的错误。
Here is what I tried.这是我试过的。 The errors are commented out next to each line.
错误在每一行旁边被注释掉。
class Graph
{
private:
template <class T>
class Vertex; // Forward Declaration
template <class T>
vector<Vertex<T> > vertices; // Err: member 'vertices' declared as a template
class Edge
{
public:
template <class T>
Vertex<T>& _orig; // Err: member '_orig' declared as a template
template <class T>
Vertex<T>& _dest; // Err: member '_dest' declared as a template
template <class T>
Edge(Vertex<T>& orig, Vertex<T>& dest) : _orig(orig), // Err: member initializer '_orig' does not name a non-static data member or base class
_dest(dest) { }
template <class T>
Vertex<T>& getOrig() { return _orig; } // Err: use of undeclared identifier '_orig'
template <class T>
Vertex<T>& getDest() { return _dest; } // Err: use of undeclared identifier '_dest'
};
template <typename T>
class Vertex
{
public:
T _data;
vector<Edge> _edges;
Vertex(T data) : _data(data) { }
void addEdgeToVertex(Edge& edge)
{
_edges.push_back(edge);
}
};
public:
template <typename T>
void addEdge(Vertex<T>& orig, Vertex<T>& dest)
{
Edge edge(orig, dest);
orig.addEdgeToVertex(edge);
dest.addEdgeToVertex(edge);
}
};
Can you please help me in pointing out what I am doing wrong?你能帮我指出我做错了什么吗? How can I fix this code?
我该如何修复此代码?
The forward declaration looks fine.前向声明看起来不错。 The problem is that you can't declare "template member variable", how could you specify the template argument for them?
问题是你不能声明“模板成员变量”,你怎么能为他们指定模板参数呢?
You should make class template instead.您应该制作 class 模板。
template <class E>
class Graph
{
private:
template <class T>
class Vertex; // Forward Declaration
vector<Vertex<E> > vertices;
...
};
It's same for class Edge
too. class
Edge
也一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.