我需要为我的类获得两个类型参数: T1 (有模板的类)和T2 (t1的模板)。
在我的例子中,顶点类型(其中一个继承自另一个)和顶点存储的数据类型(在我的例子中是name/id)。
我想写这样的东西:
template < typename VertexType < typename VertexIDType > >(这给了我错误: C2143语法错误:“缺失”,“<”之前的‘)
所以我的课会是这样的:
class Graph
{
public:
Graph(const List<VertexType<VertexIDType>>& verticesList);
VertexType<VertexIDType>& getVertexByID(const VertexIDType& ID) const;
private:
List<VertexType<VertexIDType>> vertices;
};('List‘是我的(不是std的)链接列表的实现。)
我也尝试了template <typename VertexType, typename VertexIDType>,但是在函数Graph(const List<VertexType<VertexIDType>>& verticesList);中出现了错误(C2947 C2947=‘>期望’>终止模板-参数列表,找到'<')
而这个template < typename VertexType < template <typename VertexIDType> > >
(这也给了我错误的C2143)
我真的是那种试图自己解决所有问题的人,但这让我越来越沮丧。我找不到一个我能理解是否/如何在代码中实现的答案。我现在已经完成了OOP (c++)课程。我有一些模板的经验。我已经成功地编写了获得1到2个参数的模板,但没有这样的模板。
请帮我解决这个问题,最好尽量优雅:)
谢谢。
发布于 2017-02-15 11:54:02
您可以使用模板参数:
template <template <typename> class VertexType, typename VertexIDType>
class graph;
graph<MyVertexType, MyVertexIDType> //usage或者,您可以只提取一个类型,并在部分专门化中提取ID类型:
template <typename Vertex>
class graph;
template <template <typename> class VertexType, typename VertexIDType>
class graph <VertexType<VertexIDType>> {
//...
};
graph<MyVertexType<MyVertexIDType>> //usage发布于 2017-02-15 12:49:49
TartanLlama的回答对于您提出的问题是一个很好的答案,但是您可能想稍微改变一下您的方法。如果您要求一个VertexType必须定义VertexIDType,那么您可以编写:
template <class VertexType>
class Graph
{
public:
Graph(const List<VertexType>& verticesList);
typedef typename VertexType::VertexIDType VertexIDType;
VertexType& getVertexByID(const VertexIDType& ID) const;
private:
List<VertexType> vertices;
};注意typename中用于VertexIDType的typedef。需要说“这个名称必须是一个类型,而不是一个变量”。
假设您当前的VertexType是在VertexIDType上模板化的
template <classname VertexIDType>
struct VType1 {
double stuff; // Or whatever you have in your vertex
};您需要将其更改为:
template <classname VertexIDType>
struct VType1 {
double stuff;
typedef VertexIDType VertexIDType; // Provide a typedef for VertexIDType.
};这与标准库所采用的方法类似,其中,容器的每个类型都有一个用于value_type等的This。
https://stackoverflow.com/questions/42248493
复制相似问题