Search code examples
c++templatesfriend

Class templates and friend Classes


I have Node class whice is friend with a BinaryTree class that contains an element of type Node. I want to make a BinareTree of any types, so i'm using templates on both of the classes. Like in this code :

template <class T>
class Node
{
    T value;
    Node<T> *left, *right;
    friend template <typename T> class BinaryTree; // here is the problem
};
template <class Y>
class BinaryTree{...};

What syntax do I need to you in the declaration of the friend class BinaryTree if i will use it as a template? My goal is to be able to write:

BinareTree<int> tree;

Is there any better method this that I thought of? Thanks !


Solution

  • If you lookup the syntax for template friends, you'll find the right way to do it:

    class A {
        template<typename T>
        friend class B; // every B<T> is a friend of A
    
        template<typename T>
        friend void f(T) {} // every f<T> is a friend of A
    };
    

    Although you probably just want to friend the specific one:

    friend class BinaryTree<T>;