Re: Getting non "const" pointers to object data using "const" members
Gingko wrote:
"Ulrich Eckhardt" <eckhardt@satorlaser.com> a ??crit dans le message de
news:lmgm96-su7.ln1@satorlaser.homedns.org...
struct tree {
...
template<typename Visitor>
void visit(Visitor v);
template<typename Visitor>
void visit(Visitor v) const;
};
My class system already more or less looks like that
But what is "Visitor v" ? A container for the flattened list ? Shouldn't
it be more likely something like "Visitor & v" ?
No. This is supposed to work like a functor in the STL, i.e. more or less
stateless. That way, you could e.g. use a plain function, too. What this
does is outside the scope of the above definition, in your case you would
use an adapter type that has a reference to the target container and puts
pointers to the elements there.
Note that this is not exactly the visitor pattern, since that is intended
to do double dispatch rather. The function above will invoke "v(e)" for
every node's value 'e'. This allows you to e.g. create a flat list of all
nodes, but the list will point to const objects when you use the const
overload of this function. Note that I would _not_ call it with every
node but only its value, because the node is an internal thing to the
tree.
How do you want the node to be modifiable (which is a primary requirement)
from the flattened list if the node is const or passed by value ?
Look again, there are two overloads! If you have a constant tree, all you
can get from it is references to constant elements. If you have a non-const
tree, you can also get references to non-const elements.
You really support 'tree[index]'? That tempts to write horribly
inefficient code like using a 'for(int i=0; ...)' loop to iterate
the tree.
I am actually trying to implement it as a std::vector<Node *>, filled by
pointers without ownership.
Hmm, but then you would get into trouble when inserting or deleting in the
middle. Not only do you have to adjust the parent/child pointers but you
also have to move all elements in the vector.
The only problem is, as "visit" is a "const" member, which seems more or
less logical to me, it does not allow "vNodeList.push_back(this)" for
getting the pointer.
This will probably end by removing the "const"'ness of all "visit"
members, but I don't think that this will fully satisfy me.
Use overloads for const and non-const.
Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932