2

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 !

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
Copacel
  • 1,328
  • 15
  • 25
  • Remember, the first question to ask when using `friend` is: are you really sure you need to use `friend`? – Alyssa Haroldsen May 12 '16 at 15:36
  • @Kupiakos Note, that while there are [ways to refactor a friend relation](http://stackoverflow.com/questions/27492132/how-can-i-remove-refactor-a-friend-dependency-declaration-properly), it sometimes makes sense (e.g. for sake of pragmatism), simply to use a `friend` if you know well what you're doing. – πάντα ῥεῖ May 12 '16 at 16:08
  • @Kupiakos Yes, i need to, because i want to have access to the private members of the Node class in the BinaryTree class. – Copacel May 12 '16 at 16:24

1 Answers1

4

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>;
Barry
  • 286,269
  • 29
  • 621
  • 977
  • [Note that different template parameter names are required](http://coliru.stacked-crooked.com/a/0495156f9adb8f27) when `class A` is a template class itself. – πάντα ῥεῖ May 12 '16 at 16:04