模板类的实例化是错误的

时间:2012-05-13 09:38:26

标签: c++ templates instantiation

g ++编译器提示以下语句错误:

template<typename Type>
class SingleList{
public:
    SingleList()
        {
            head =  new SingleListNode<Type> () ;    //Error happens here!!!
        }

错误消息是:

 ./inc/single_list.h: In instantiation of ‘SingleListNode<int>’:
./inc/single_list.h|39 col 13| instantiated from ‘SingleList<Type>::SingleList() [with Type = int]’

head的定义如下,或许问题与此无关。

SingleListNode<Type> *head;

SingleList函数中类main的实例化是:

int main()
{
    SingleList<int> list;

我不知道语法错误发生在哪里,任何人都可以帮助我吗?谢谢!

=============================================== =========================

以下是源文件的内容:

    template<typename Type> class SingleList;

template<typename Type> class SingleListNode{
private:
    friend class SingleList<Type>;

    SingleListNode() : next(NULL){}

public:
    friend ostream& operator<< <Type>(ostream& os,SingleListNode<Type>& sln);             //Error here!!

private:
    SingleListNode *next;
};

template<typename Type> ostream& operator<<(ostream& os,SingleListNode<Type>& out){
    os<<out.data;
    return os;
}

template<typename Type> class SingleList{
public:
    SingleList()
        {
            head =  new SingleListNode<Type> () ;              //Error happens here.
        }
    ~SingleList(){
        delete head;                                       //Same error
    }

private:
    SingleListNode<Type> *head;
};

g ++提示的错误消息

|| g++ -g -I ./inc/ -c single_list_test.cpp  -o single_list_test.o
|| single_list.h: In instantiation of ‘SingleListNode<int>’:
single_list.h|25 col 13| instantiated from ‘SingleList<Type>::SingleList() [with Type = int]’
single_list_test.cpp|9 col 18| instantiated from here
single_list.h|10 col 18| error: template-id ‘operator<< <int>’ for ‘std::ostream& operator<<(std::ostream&, SingleListNode<int>&)’ does not match any template declaration
|| make: *** [single_list_test.o] Error 1

1 个答案:

答案 0 :(得分:1)

到我的gcc,只需修改以下语句

friend ostream& operator<< <Type>(ostream& os,SingleListNode<Type>& sln)

 friend ostream& operator<< (ostream& os,SingleListNode<Type>& sln)