小编Dro*_*man的帖子

嵌套模板(即模板 <typename T< typename templateArgumentFor_T >>)

我需要为我的类获取 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 个参数的模板,但没有这样的。

请帮我解决这个问题,最好尽可能优雅:)

谢谢。

c++ templates

3
推荐指数
1
解决办法
1652
查看次数

使用类型定义-基于模板参数的类-类的超出范围

typedef在类函数的声明和定义中,如何使用基于类的模板参数的?

假设我的课是:

template<class T>
class A
{
    typedef T::T1 X;
    typedef T::T2 Y;

    X& f1(Y& y);
    Y& f2(Y& y);

    // More declarations
};
Run Code Online (Sandbox Code Playgroud)

因此,在定义中,我不能只写:

typedef typename T::T1 X;
typedef typename T::T2 Y;

template<class T>
X& A<T>::f1(Y& y) {...}

template<class T>
Y& A<T>::f2(Y& y) {...}
Run Code Online (Sandbox Code Playgroud)

(在我的情况TMaxSimplePathVertex<VertexType<VertexIDType>>,我有3种类型定义,所以它真的很麻烦)。

我想我可以将所有typedef复制每个函数定义中,但这似乎不是一个很好的解决方案。

而且,当然可以#define X T1,但是通常我会听到人们建议不要使用#define这些东西。

那么最好的解决方案是什么?

c++ parameters templates typedef

2
推荐指数
1
解决办法
245
查看次数

标签 统计

c++ ×2

templates ×2

parameters ×1

typedef ×1