c++之将当前模板用作模板参数之一的模板参数

Leo_wl 阅读:52 2025-01-19 22:14:33 评论:0

我正在尝试创建一个通用的图形结构,但我遇到了顶点和边之间的这种循环依赖关系。我像这样定义我的 Vertex 和 Edge 类:

template<typename EdgeType> 
struct Vertex { 
    std::vector<EdgeType> successors; 
}; 
 
template<typename EdgeCostType, typename VertexWrapper> 
struct Edge { 
    EdgeCostType cost; 
    VertexWrapper source; 
    VertexWrapper dest; 
}; 

我想用类似 Vertex<Edge<int, std::shared_ptr<decltype(v)>>> v; 的东西来实例化它,但我显然不能。我能做些什么来解决这种循环依赖?

编辑:

我认为这个问题归结为使用当前模板作为当前模板的模板参数之一的模板参数,例如如何做这样的事情:

template<typename VertexWrapper> 
struct Vertex { 
    std::vector<pair<int, VertexWrapper<Vertex>>> successors; 
}; 

请您参考如下方法:

使用模板模板参数,您可以执行以下操作:

template<typename EdgeType> 
struct Vertex { 
    std::vector<EdgeType> successors; 
}; 
 
template<typename EdgeCostType, template <typename> class VertexWrapper> 
struct Edge { 
    EdgeCostType cost; 
    VertexWrapper<Edge> source; 
    VertexWrapper<Edge> dest; 
}; 
 
 
using myEdge = Edge<double, Vertex>; 
using myVertex = Vertex<myEdge>; 


标签:C++
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号