1

I am trying to write a template for a class. This class uses a Node class within it so I have defined the Node class as having the List class as a friend. See below.

template <typename T>
class Node {
    private:
        Node() {
            next = nullptr;
            prev = nullptr;
        }

        Node(int data) : Node() { this->data = data; }

        Node *next;
        Node *prev;
        int data;

        friend class DoubleLinkedList;
    };

template<typename T>
    class DoubleLinkedList {

    public:
        DoubleLinkedList();

        ~DoubleLinkedList();

    private:
        Node *_head;
        Node *_tail;

    };

I have another file where the classes are implemented. I get this error with or without the template definition above the List class. Can someone explain this?

  • My rule of thumb when befriending a template is to copy that template’s signature exactly. In this case something like `template friend class List;` might help you – alter_igel Oct 15 '19 at 20:38
  • @alterigel The above will friend *all* instantiations of `List`. I.e. `List` will have full access to `Node`. Careful what you wish for; you just might get it. – WhozCraig Oct 15 '19 at 20:40
  • 1
    Tiffany can we see *real* code ? I ask because without a forward declaration that `Node` shouldn't even compile (it should error to the effect of specializing a non-existent template class). Regardless, *prior* to that `Node` template decl, you should be able to forward decl `List`, as in `template class List;` and this should work. – WhozCraig Oct 15 '19 at 20:42
  • 1
    https://stackoverflow.com/questions/8967521/class-template-with-template-class-friend-whats-really-going-on-here – macroland Oct 15 '19 at 20:43
  • 2
    The trick in your case would be forward declaration of `template class List;` before Node. – macroland Oct 15 '19 at 20:48
  • @macroland Thank you for the link! That was really helpful! – Tiffany Montgomery Oct 15 '19 at 20:54

1 Answers1

0

This works for me:

template <typename T>
class Node
{
private:
    Node()
    {
        next = nullptr;
        prev = nullptr;
    }

    Node(int data) : Node() { this->data = data; }

    Node *next;
    Node *prev;
    int data;

    template<typename T> friend class DoubleLinkedList;
};

template<typename T>
class DoubleLinkedList
{

public:
    DoubleLinkedList();

    ~DoubleLinkedList();

private:
    Node<T> *_head;
    Node<T> *_tail;

};
Markus Schumann
  • 7,636
  • 1
  • 21
  • 27