I am writing my own implementation of a templated Graph
class in C++ and so I am also implementing templated Vertex
and Edge
classes. Thus, the implementations have to be inside their respective header file and not inside separate .cpp
files. (The top answer here won't work for me)
My Vertex
class stores an adjacency list of out-edges as a vector
of Edge
s and the Edge
class stores pointers to the source and destination Vertex
s as well as the weight of the edge.
Since Edge
only stores pointers to Vertex
, it is sufficient to forward declare the Vertex
class in Edge.h
. Then I can #include "Edge.h"
at the top of Vertex.h
.
Is this the best way to resolve the co-dependencies of the Vertex
and Edge
classes? The user will have to #include
both files in order to use either one (i.e. in Graph.h
).
What if users want to use Vertex
without having to also explicitly include Edge.h
or vice versa? Should I forward declare and #include
each inside the other?
Or should I implement them in the same header file?
How, if at all, is this problem addressed in STL?
Here's what I have right now:
Edge.h:
#ifndef _EDGE_H__
#define _EDGE_H__
template <class T> class Vertex;
template <class T>
class Edge
{
private:
Vertex<T>* _source;
Vertex<T>* _dest;
unsigned long long _weight;
...
};
#endif
Vertex.h:
#ifndef _VERTEX_H__
#define _VERTEX_H__
#include "Edge.h"
#include <vector>
template <class T>
class Vertex
{
private:
std::vector<Edge<T> > _adj;
...
};
#endif