简体   繁体   English

模板朋友类:前瞻声明或......?

[英]Template Friend Class: Forward Declaration or…?

Suppose I have a template class that I am trying to declare as a friend class. 假设我有一个模板类,我试图将其声明为朋友类。 Should I forward declare the class or give it its own template? 我应该转发声明类还是给它自己的模板?

Example: 例:

template <typename E>
class SLinkedList;
template <typename E>
class SNode {
private:
  E elem;
  SNode<E>* next;
  friend class SLinkedList<E>;
};

Or 要么

template <typename E>
class SNode {
private:
  E elem;
  SNode<E>* next;
  template <typename T>
  friend class SLinkedList;
};

Your first approach is probably what you want. 你的第一种方法可能就是你想要的。 It will make SLinkedList<int> a friend of SNode<int> , and similar for all matching types. 这将使SLinkedList<int>朋友SNode<int> ,并为所有匹配的类型相似。

Your second approach will make every SLinkedList a friend of every SNode . 你的第二个方法将尽一切SLinkedList每一个朋友SNode This is probably not what you want as SLinkedList<Widget> has no business touching the private parts of an SNode<int> 这可能不是你想要的,因为SLinkedList<Widget>没有触及SNode<int>的私有部分的业务


A different approach I could recommend would be to make SNode a nested class. 我可以推荐的另一种方法是使SNode成为嵌套类。 This is pretty common for data structures consisting of nodes: 这对于由节点组成的数据结构非常常见:

template <typename E>
class SLinkedList {
    struct SNode {
        E elem;
        SNode* next;
    };
};

With this scheme you may as well get rid of the friend declaration and have everything in SNode be public, because the whole class would be private to SLinkedList 使用这个方案你也可以摆脱朋友声明并让SNode所有SNode都是公开的,因为整个类都是私有的SLinkedList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM