将用户定义的类作为模板参数传递

时间:2014-06-26 06:39:27

标签: c++

我正在尝试用C ++实现Graph 我已经定义了一个类Edge,它将节点名称和权重作为2个参数 还有一个类Graph,当我尝试将Edge作为模板参数传递给图形声明Graph<int,Edge> g时,我收到了一个错误。
我不能将类作为模板参数传递。我是C ++编码的新手,所以请原谅我任何愚蠢。任何人都可以建议正确的方法吗?

template<class T1,class T2>
    class Edge{
        T1 d_vertex;
        T2 d_weight;
        public:
        Edge(T1,T2);
        T1 vertex();
        T2 weight();
};
template<class T1,class T2>
Edge<T1,T2>::Edge(T1 v,T2 w):d_vertex(v),d_weight(w){
}
template<class T1,class T2>
T1 Edge<T1,T2>:: vertex(){
        return d_vertex;
}
template<class T1,class T2>
T2 Edge<T1,T2>::weight(){
        return d_weight;
}
template<class T,class T2>
class Graph{
        vector<pair<T, list<T2> > > node;

};

int main()
{
    Graph<int,Edge> g;
}

1 个答案:

答案 0 :(得分:2)

在此实例化中

Graph<int,Edge> g;

Edge仍然是类模板。这意味着您的Graph类应该是那样的

template<class T, template<class,class> class T2>
class Graph{ /**/ };

即拥有模板模板参数,您应指定Edge的类型,例如

Graph<int, Edge<int,int>> g;
相关问题