2016-05-12 188 views
2

我有節點類whice是包含Node類型元素的BinaryTree類的朋友。我想製作任何類型的BinareTree,所以我在兩個類上都使用了模板。像這樣的代碼:類模板和朋友類

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

什麼語法我需要你在朋友類BinaryTree的聲明,如果我將它用作模板? 我的目標是能寫:

BinareTree<int> tree; 

有沒有更好的方法,這一點,我想的? 謝謝!

+0

記住,在使用'friend'時要問的第一個問題是:你確定你需要使用'friend'嗎? – Kupiakos

+0

@Kupiakos注意,儘管有[重構朋友關係的方式](http://stackoverflow.com/questions/27492132/how-can-i-remove-refactor-a-friend-dependency-declaration-properly) ,它有時是有意義的(例如爲了實用主義),只要你知道你在做什麼,就簡單地使用「朋友」。 –

+0

@ Kupiakos是的,我需要,因爲我想訪問BinaryTree類中Node類的私有成員。 – Copacel

回答

4

如果您查找的語法template friends,你會發現這樣做的正確方法:

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

雖然你可能只是想朋友的具體之一:

friend class BinaryTree<T>; 
+0

[請注意,不同的模板參數名稱是必需的](http://coliru.stacked-crooked.com/a/0495156f9adb8f27)當'class A'本身就是一個模板類。 –