【问题标题】:Implicit instantiation of undefined template未定义模板的隐式实例化
【发布时间】:2013-03-23 05:08:27
【问题描述】:

这是我正在尝试编写的模板(队列):

#include <iostream>

using namespace std;

template <typename T>
class Queue
{
    friend ostream& operator<< (ostream &, const Queue<T> & );
private:
    template<class> class Node;
    Node<T> *front;
    Node<T> *back;
public:
    Queue() : front(0), back(0) {}
    ~Queue();
    bool Empty()
    {
        return front == 0;
    }
    void Push(const T& NewEl)
    {
        Node<T&> *El = new Node<T> (NewEl);
        if (Empty())
            front=back=El;
        else
        {
            back-> next = El;
            back = El;
        }
    }
    void Pop()
    {
        if (Empty())
            cout << "Очередь пуста." << endl;
        else
        {
            Node<T> *El = front;
            front = front -> next;
            delete El;
        }
    }
    void Clear()
    {
        while (! Empty())
            Pop();
    }
};

template <typename T>
class Node
{
    friend class Queue<T>;
public:
    Node() {next = 0;}
    Node(T nd) {nd=node; next=0;}
    T& getsetnode(){return node;}
    Node<T>*& getsetnext(){return next;}
private:
    T front;
    T back;
    T node;
    Node<T> *next;
};

template <class T> ostream& operator<< (ostream &, const Queue<T> & );

int main()
{
    Queue<int> *queueInt = new Queue<int>;
    for (int i = 0; i<10; i++)
    {
        queueInt->Push(i);
        cout << "Pushed " << i << endl;
    }
    if (!queueInt->Empty())
    {
        queueInt->Pop();
        cout << "Pop" << endl;
    }
    queueInt->Front();
    queueInt->Back();
    queueInt->Clear();
    cout << "Clear" << endl;
    return 0;
}

在这些行:

    Node<T&> *El = new Node<T> (NewEl);

    front = front -> next;
    delete El;

我收到Implicit instantiation of undefined template 'Queue&lt;int&gt;::Node&lt;int&gt;'。我究竟做错了什么?阅读this post 后,我尝试将int 更改为const int 以查看是否是问题所在,但显然不是,因为我遇到了同样的错误。

我正在使用带有 LLVM 编译器 4.2 的 XCode。当我切换到 GCC 时,我收到更多错误:

template&lt;class&gt; class Node; 得到Declaration of 'struct Queue&lt;int&gt;::Node&lt;int&gt;'Node&lt;T&amp;&gt; *El = new Node&lt;T&gt; (NewEl); 得到 Invalid use of incomplete type, 并且任何处理将任何内容分配给 El 的内容都无法将 &lt;int&amp;&gt;* 转换为 &lt;int&gt;*(但删除引用不会改变 LLVM 的任何内容)。

【问题讨论】:

    标签: c++ templates


    【解决方案1】:
    template <typename T>
    class Queue
    {
    private:
        template<class> class Node;
    /* ... */
    

    这是Queue::Node 的前向声明。后者定义的class Node 在全局命名空间中,所以它们不一样,任何Queue::Node 的使用都会导致类型不完整的错误。由于您无论如何都不提供内部节点的接口,所以只需废弃Node 的全局定义并将其粘贴到Queue 中:

    template <typename T>
    class Queue
    {
    private:
        class Node
        {
        public:
        Node() {next = 0;}
        /* ... */
         };
    /* ... */
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 2013-08-10
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多