首页 > 解决方案 > 错误 C2440:无法转换模板类中的类型......即使它是相同的类型?

问题描述

我正在使用一个模板类List,其中定义了两个类 -NodePosition

template <class T>
class List {
public:
    // Nodes in the linked list
    struct Node {
        Node *prev;
        Node *next;
        T    item;

        Node() : prev(NULL), next(NULL) {
        }

        Node(T item) : prev(NULL), next(NULL) {
            this->item = item;
        }

        T Item() const { return item; }
    };

    // Object for enumerating the list.
    class POSITION {
        friend class List<T>;

    public:
        POSITION() : pNode(NULL) {
        }

        bool operator==(const POSITION &p) const {
            return pNode == p.pNode;
        }

        bool operator!=(const POSITION &p) const {
            return pNode != p.pNode;
        }

    private:
        typename List<T*>::Node* pNode;

        POSITION(Node *p) : pNode(p)  {
        }
    };

    List() {
        m_anchor.next = &m_anchor;
        m_anchor.prev = &m_anchor;

        m_count = 0;
    }

    POSITION Next(const POSITION pos) {
        if (pos.pNode && (pos.pNode->next != &m_anchor)) {
            return POSITION(pos.pNode->next);
        }
        else {
            return POSITION(NULL);
        }
    }

    protected:
        Node    m_anchor;  // Anchor node for the linked list.
        DWORD   m_count;   // Number of items in the list.
};

当我尝试编译这个类时,我得到一个错误 C2440:

'<function-style-cast>': cannot convert from 'List<T*>::Node*' to 'List<T*>::Node*'

它指向函数内的行List::Next(const Position pos)

return POSITION(pos.pNode->next);

我感到困惑的是错误消息 - 当它们是相同类型时,似乎没有任何理由List<T*>::Node*无法将 a 转换为 a List<T*>::Node*......我想这是由于模板类我可能需要一个typename地方,但我不完全确定这里发生了什么。

标签: c++templatesc++17typename

解决方案


推荐阅读