I am trying to create a Graph
class by using Nested Classes Vertex
and Edge
. I want to make my Vertex
class to accept generic parameters. I have forward declared my Vertex
class so that I can use it in my 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.
template <class E>
class Graph
{
private:
template <class T>
class Vertex; // Forward Declaration
vector<Vertex<E> > vertices;
...
};
It's same for class Edge
too.