如何在c++中使用嵌套类模板
How to use templates with Nested class in C++
我正在尝试使用嵌套类的模板。我不确定如何从另一个类访问内部类的类类型。
示例代码如下。
// I have a List class that can accept any type. It has an inner class
template <class T>
class List
{
public:
class Node
{
public:
T data;
Node* next;
Node* prev;
};
void addElement(Node& value);
private:
Node* head;
};
// Here I am making an array of Lists
template <class T>
class ListArray
{
public:
// Here is my question.
void add(Node& value); // How to give "Node" class type here ?
private:
List<T> _listArr[10];
};
// Is the below the right way to define ListArray::add, especially the way in which Node type can be passed to it ?
template <class T>
void ListArray<T>::add(List<T>::Node& value)
{
// Make a call to List::addElement and pass Node& value
_listArr[0].addElement(value);
//....
}
你能告诉我如何才能实现上述目标吗?谢谢。
Node
是类模板的嵌套类型:
template <class T>
class ListArray
{
public:
typedef typename List<T>::Node Node_type;
void add(Node_type& value); // Refer to it as Node_type
private:
List<T> _listArr[10];
};
:
template <class T>
void ListArray<T>::add(typename ListArray<T>::Node_type& value)
{
_listArr[0].addElement(value);
//....
}
我使用typedef
定义节点类型的本地名称。这是非常有用的-现在,ListArray
的客户端可以编写代码,显式地使用Node_type
(不知道它实际上是什么)。这种技术在std
库中大量使用——通常,std::
类型有吨类型定义,以允许编写灵活的代码。
另外,请注意typename
关键字——在类模板的嵌套类型的情况下,它是必需的。它表明,给定的名称是类型的名称(没有它,您应该得到一个编译器错误)。
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 用C#中的并集模拟C++嵌套结构
- 部分专业化和嵌套模板
- 嵌套While循环不起作用(C++问题)
- C++-模板嵌套类的引用初始化无效
- 如何在嵌套类中正确使用友元声明?
- UE4 C++ 我无法将 JSON 嵌套值获取到 TArray