另一个模板循环依赖问题
Yet another template circular dependency issue
我正在尝试创建一个基于面向对象的模板的通用图形结构,但是在我的设计中,我遇到了一个可能的循环依赖关系,我不知道如何避免。
我按如下方式定义我的顶点和边类:
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
相关文章:
- node-gyp 的先有鸡还是先有蛋的问题:指向依赖项中的头文件
- 在包含窗口标头时难以解决循环依赖关系问题
- C++ 中的循环依赖关系问题
- 交叉依赖项类的问题
- "std::shared_ptr"循环依赖关系是如何导致问题的
- 生成的依赖项问题
- C++ API-MS-WIN-SERVICE-PRIVATE-L1-1-1.DLL依赖项问题
- 是库依赖问题可以通过接口避免
- 另一个模板循环依赖问题
- 命名空间内类的循环依赖问题
- 交叉编译助推 1.60.0 内部依赖问题
- 使用发布 CRT 在调试中构建应用程序,并在提升时存在依赖问题
- 循环依赖问题
- 循环依赖问题
- c++:循环依赖问题
- c++ -构建顺序和依赖问题
- brew install glew 没有解决我的 <GL/glew.h>依赖问题
- 你能用C++解决这个循环依赖问题吗
- 类的相互依赖问题
- 在使用模板时避免循环依赖问题