我需要为我的类获取 2 个类型参数:T1(具有模板的类)和 T2(T1 模板的参数)。
在我的例子中,有一个 Vertex 类型(有 2 个,一个从另一个继承),以及顶点存储的数据类型(在我的例子中是 name/id)。
我希望能够写出这样的东西:
template < typename VertexType < typename VertexIDType > >
Run Code Online (Sandbox Code Playgroud)
(这给了我错误:C2143语法错误:在“<”之前缺少“,”)
这样我的课程就会是这样的:
class Graph
{
public:
Graph(const List<VertexType<VertexIDType>>& verticesList);
VertexType<VertexIDType>& getVertexByID(const VertexIDType& ID) const;
private:
List<VertexType<VertexIDType>> vertices;
};
Run Code Online (Sandbox Code Playgroud)
(“List”是我的(不是标准的)链表实现。)
我也尝试过template <typename VertexType, typename VertexIDType>
,但后来我在函数中遇到错误Graph(const List<VertexType<VertexIDType>>& verticesList);
(C2947期望'>'终止模板参数列表,发现'<')
和这个template < typename VertexType < template <typename VertexIDType> > >
(这也给了我错误 C2143)
我确实是那种凡事都想自己解决的人,但这让人沮丧。我找不到我理解是否/如何在我的代码中实现的答案。我现在已经完成了 OOP (c++) 课程。我对模板有一些经验。我编写过可以成功获取 1 或 2 个参数的模板,但没有这样的。
请帮我解决这个问题,最好尽可能优雅:)
谢谢。
您可以使用模板模板参数:
template <template <typename> class VertexType, typename VertexIDType>
class graph;
graph<MyVertexType, MyVertexIDType> //usage
Run Code Online (Sandbox Code Playgroud)
或者,您可以只采用一个类型并以部分特化的方式提取 ID 类型:
template <typename Vertex>
class graph;
template <template <typename> class VertexType, typename VertexIDType>
class graph <VertexType<VertexIDType>> {
//...
};
graph<MyVertexType<MyVertexIDType>> //usage
Run Code Online (Sandbox Code Playgroud)