另一个模板循环依赖问题

Yet another template circular dependency issue

本文关键字:依赖 问题 循环 另一个      更新时间:2023-10-16

我正在尝试创建一个基于面向对象的模板的通用图形结构,但是在我的设计中,我遇到了一个可能的循环依赖关系,我不知道如何避免。

我按如下方式定义我的顶点和边类:

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 个表示源顶点和目标顶点的引用。

如果要填写顶点模板参数,我需要了解边的类型。为了知道边的类型,我需要知道顶点的类型。

知道如何解决这个问题吗?

有一种解决方案可以解决类模板之间的相互依赖关系。但在考虑之前,我通常会问自己:"我不应该把它解耦吗?事实上,这可能是一个糟糕的设计。但有时,它是模型的一部分。您的案例(图表)就是一个例子。

解决方案基于概念级别的解耦,并引入了一个中间模板类型,该模板类型将嵌入并了解两种类型(顶点和边缘)并打破循环。

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;
}

http://ideone.com/FrBqcb

您将在那些关于高级C++技术的非常好的讲义中找到对该解决方案的广泛解释。

您可以在

使用类解决循环依赖之前预先宣布该类,如下所示:

class basic_vertex;

无论是否是模板,它都是与类的循环依赖相同的问题。您的一个类必须能够仅使用指向另一个类的指针/引用。前向声明类边缘;在basic_vertex中使用边缘*在边缘中使用basic_vertex