問題描述
假設我正在為二叉樹創建一個類 BT
,并且我有一個描述樹元素的類 BE
,類似于
Let's say I'm creating a class for a binary tree, BT
, and I have a class which describes an element of the tree, BE
, something like
template<class T> class BE {
T *data;
BE *l, *r;
public:
...
template<class U> friend class BT;
};
template<class T> class BT {
BE<T> *root;
public:
...
private:
...
};
這似乎有效;但是我對下面發生的事情有疑問.
This appears to work; however I have questions about what's going on underneath.
我最初嘗試將朋友聲明為
I originally tried to declare the friend as
template<class T> friend class BT;
然而,這里似乎有必要使用 U
(或除 T
以外的其他東西),這是為什么呢?這是否意味著任何特定的 BT
是任何特定 BE
類的朋友?
however it appears necessary to use U
(or something other than T
) here, why is this? Does it imply that any particular BT
is friend to any particular BE
class?
關于模板和朋友的 IBM 頁面提供了不同類型的函數朋友關系的示例,而不是類(并且猜測語法尚未收斂到解決方案上).我更愿意了解如何為我希望定義的朋友關系類型獲得正確的規范.
The IBM page on templates and friends has examples of different type of friend relationships for functions but not classes (and guessing a syntax hasn't converged on the solution yet). I would prefer to understand how to get the specifications correct for the type of friend relationship I wish to define.
推薦答案
template<class T> class BE{
template<class T> friend class BT;
};
不允許,因為模板參數不能相互遮蔽.嵌套模板必須具有不同的模板參數名稱.
Is not allowed because template parameters cannot shadow each other. Nested templates must have different template parameter names.
template<typename T>
struct foo {
template<typename U>
friend class bar;
};
這意味著 bar
是 foo
的朋友,而不管 bar
的模板參數如何.bar
、bar
、bar
和任何其他 bar
都是朋友foo
.
This means that bar
is a friend of foo
regardless of bar
's template arguments. bar<char>
, bar<int>
, bar<float>
, and any other bar
would be friends of foo<char>
.
template<typename T>
struct foo {
friend class bar<T>;
};
這意味著當 bar
的模板參數匹配 foo
的模板參數時,bar
是 foo
的朋友.只有 bar
是 foo
的朋友.
This means that bar
is a friend of foo
when bar
's template argument matches foo
's. Only bar<char>
would be a friend of foo<char>
.
在您的情況下,friend class bar
應該就足夠了.
In your case, friend class bar<T>;
should be sufficient.
這篇關于類模板與模板類朋友,這里到底發生了什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!