Hello folks!
First I'd like to explain myself saying that I know there are already a lot of threads discussing this topic, but I found myself totally lost among them. Each gave me different answer and none was correct.
Nevertheless, if there is already a good answer to my question, please post a link to it.
I'll try to express my problem clearly.
In my programme I'm creating two template classes. A good example can be a BST tree:
1 2 3 4 5 6 7 8 9 10 11 12
|
template <class T>
class BSTNode {
T value;
T *parent, *left, *right;
BSTNode<T>();
};
template <class T>
class BSTTree {
BSTNode<T> root;
//some useful methods here
};
|
A little explanation
I
do want to have all fields (variables) in
BSTNode private and I
don't want any public methods in it.
This is because I want
BSTTree to be the only class permitted to make any use of
BSTNode. This is also the reason why the default constructor in
BSTNode is private.
Now, to achieve my goal I want to declare
BSTTree as a friend class of
BSTNode. I can do it this way:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
template <class T>
class BSTNode {
T value;
T *parent, *left, *right;
BSTNode<T>();
template <class U> friend class BSTTree;
};
template <class T>
class BSTTree {
BSTNode<T> root;
//some useful methods here
};
|
What my problem is
I want to make my code more secure. Because
<class U>
means any type it is possible, for instance, for a
BSTTree<std::string>
to access fields of a
BSTNode<int>
This is the type of situation I want to prevent. I want each instance of
BSTNode class to be accessible only by an instance of
BSTTree class with the same
T types.
Unfortunately, I can't do the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
//CAUTION!
//faulty code below!
template <class T>
class BSTNode {
T value;
T *parent, *left, *right;
BSTNode<T>();
//the line below produces an error
//the only change is substituting 'U' for 'T'
template <class T> friend class BSTTree;
};
template <class T>
class BSTTree {
BSTNode<T> root;
//some useful methods here
};
|
G++ gives me an error:
BSTree.cpp:11: error: declaration of `class T'
BSTree.cpp:4: error: shadows template parm `class T' |
Finally, the question
What is the proper way of solving this problem?
Is there a proper friend class declaration to use?
If no, what is another way of doing this?
Cheers,
Paul
PS. I know that I can simply be careful to use the code in the way I want. But to feel safe I want the compiler to take care of it.