I have come across this problem several times and would like to know if there is a simple method or template that I can use to solve it.
Imagine a tree structure in which each node contains an STL container (vector) of pointers to child elements. I want client code to be able to navigate this tree and iterate over child containers to access other parts.
My problem is that I want to support encapsulation for my nodes, while at the same time allowing clients to easily see all the children for this node. I also want to make sure that if the client gets a link to const in the root directory of the node in the tree, then access to subsequent parts of the tree is also constant.
Should I try to create an iterator class for my node type, try using the node tag method, or is there a more elegant template that I am missing?
Edit: I want to emphasize once again that while I see some good ideas, I have containers with pointers for other nodes. The return vector<node *>::const_iteratorwill not impede client calls by non-constant methods on the node. It protects only pointers from pointing to different objects.
source
share