我正在尝试创建一个基于通用图形结构的面向对象模板,但是在我的设计中我遇到了一个可能的循环依赖,我不确定如何避免。
我按如下方式定义我的顶点和边类:
template <class label_type, class edge_type>
class basic_vertex { .. }
template <class vertex_type, class weight_type = std::int32_t>
class basic_edge { .. }
在顶点类中,我通过将指向它们的指针存储在 std::list 中来跟踪附加到节点的内边和外边。
在边对象中,我保留了 2 个引用,分别表示源顶点和目标顶点。
如果我要填写顶点模板参数,我需要知道边的类型。为了知道边的类型,我需要知道顶点的类型。
知道如何解决这个问题吗?
最佳答案
有一种解决方案可以解决类模板之间的相互依赖关系。但在考虑之前,我通常会问自己:“我不应该把它解耦吗?”事实上,这可能是一个糟糕的设计。但有时,它是模型的一部分。你的案例,图表,就是一个例子。
该解决方案基于概念级别的解耦,并引入了一种中介模板类型,该类型将嵌入并了解两种类型(顶点和边)a 并打破循环。
template <typename T_graph, typename T_label>
struct vertex_tmpl {
typedef typename T_graph::edge_t edge_t;
edge_t* edge;
// .... maybe some more edges ....
};
template <typename T_graph, typename T_weight>
struct edge_tmpl {
typedef typename T_graph::vertex_t vertex_t;
vertex_t* vertex;
};
template < template <typename, typename> class T_vertex,
template <typename, typename> class T_edge,
typename T_weight = int,
typename T_label = int >
struct graph_tmpl {
typedef graph_tmpl< T_vertex, T_edge> self_t;
typedef T_vertex<self_t, T_label> vertex_t;
typedef T_edge<self_t, T_weight> edge_t;
};
int main() {
typedef graph_tmpl< vertex_tmpl, edge_tmpl> graph_t;
typedef typename graph_t::edge_t basic_edge;
typedef typename graph_t::vertex_t basic_vertex;
basic_edge edge;
basic_vertex vertex;
vertex.edge = &edge;
edge.vertex = &vertex;
}
您将在 those very good lecture notes about advanced C++ technics 中找到对解决方案的详尽解释。 .
关于c++ - 另一个模板循环依赖问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13800850/