templates - 如何删除错误: X is not a class template

标签 templates c++11

我不是使用模板的专家,但我不确定为什么我会得到 error: 'SLinked_List' is not a class template: friend class SLinked_List<T>;在类的定义中SNode 。这段代码有什么问题?

谢谢你, 普拉纳夫

#include <iostream>
#include <string>

template <typename T>
class SNode{
    friend class SLinked_List<T>;
private:
    T data;
    SNode<T>* next;
};

template <typename T>
class SLinked_List{

private:
    SNode<T>* head;

public:
    SLinked_List(){
        head = nullptr;
    }

    bool empty() const { return head == nullptr; }

    void insert_first (const T&);

};

template <typename T>
void SLinked_List<T> :: insert_first (const T& t){
    SNode<T>* node = new SNode<T>;
    node->data = t;
    node->next = head;
    head = node;
}

int main(){

    SLinked_List<std::string> ls;

    ls.insert_first("Hello");

    return 0;
}

最佳答案

当您使用模板参数来引用名称时,您是在说该类型已经作为模板存在,并且我想引用该模板的特定特化。在 SNode 内部,SLinked_List 尚未声明,因此这是不允许的,因为编译器甚至不知道它是否是模板。

很明显,您希望与采用 T 的特化成为 friend ,因此您需要在 SNode 之前声明 SLinked_List:

template <typename T>
class SLinked_List;

template <typename T>
class SNode{
    friend class SLinked_List<T>;
private:
    T data;
    SNode<T>* next;
};

现在编译器知道 SLinked_List 是一个模板,可以这样引用。

关于templates - 如何删除错误: X is not a class template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30417524/

相关文章:

c++ - 将模板指针传递给 memcpy

C++: "specializing"一个成员函数模板,用于从某个基类派生的类

c++ - 通过 const 引用获取字符串

c++ - 好友模板功能说明

c++ - 如果它是模板类,是否可以隐藏库依赖项?

c++ - 如何过早销毁智能指针

c++ - std::array 的类型特征

c++ - std::map::emplace 语法问题

C++后缀评估问题

c++ - 什么时候必须声明模板中使用的函数?