如何在c++中使用嵌套类模板

How to use templates with Nested class in C++

本文关键字:嵌套 c++      更新时间:2023-10-16

我正在尝试使用嵌套类的模板。我不确定如何从另一个类访问内部类的类类型。

示例代码如下。

// 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关键字——在类模板的嵌套类型的情况下,它是必需的。它表明,给定的名称是类型的名称(没有它,您应该得到一个编译器错误)。