Search code examples
c++templatesfriend-class

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;
};

Solution

  • Your first approach is probably what you want. It will make SLinkedList<int> a friend of SNode<int>, and similar for all matching types.

    Your second approach will make every SLinkedList a friend of every SNode. This is probably not what you want as SLinkedList<Widget> has no business touching the private parts of an SNode<int>


    A different approach I could recommend would be to make SNode a nested class. 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