使用当前模板作为模板参数之一作为模板参数

问题描述 投票:6回答:3

我正在尝试建立一个通用的图结构,但是我遇到了顶点和边之间的这种循环依赖关系。我像这样定义我的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;
};
c++ c++11 c++17 circular-dependency
3个回答
9
投票

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

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

3
投票

您只是简单地工作..(但是我不知道如何打印和初始化成员向量)

#include <vector>
#include <iostream>  
using namespace std;

template<typename EdgeType>
struct Vertex {
    vector<EdgeType> successors;
};

template<typename EdgeCostType, typename VertexWrapper>
struct Edge {
    EdgeCostType cost;
    VertexWrapper source;
    VertexWrapper dest;
};

int main (){

    Vertex<int> vertx = {{5}};
    Edge<int, decltype(vertx)> ed = {7};

    cout<< ed.cost <<"\n";     //cout<< ed.dest.successors<<"\n";   // not work, ask help!
}

0
投票

Jarod42's answer可以使用,但确实会限制您只能翻倍。例如,如果您想要一个更灵活的接受int的选项,则也可以使用以下选项:

template<class T>
using myEdge = Edge<T, Vertex>;

template<class T>
using myVertex = Vertex<myEdge<T>>;

这将允许您使用其他类型的数字,如果出于某些原因您需要简化的数字。然后使用双打看起来像这样:

myVertex<double> v;
© www.soinside.com 2019 - 2024. All rights reserved.