digitalmars.D.learn - Applying const to an object but not the container (D 2.0)
- Burton Radons <burton.radons gmail.com> May 23 2009
- div0 <div0 users.sourceforge.net> May 24 2009
I'm writing an XML class. There are two tests for this class, isAncestorOf and
isDescendantOf, that are implemented in terms of one another. They're both
const, and look like this:
class Node
{
Node parentNode;
/// ...
/// Return whether this is an ancestor of the other node. A node is not an
ancestor of itself, or of null.
bool isAncestorOf (Node node) const
{
while (node) if ((node = node.parentNode) is this)
return true;
return false;
}
/// Return whether one of the parents of this node is the other. A node is not
a descendant of itself, or of null.
bool isDescendantOf (Node node) const
{
return node ? node.isAncestorOf (this) : false;
}
}
The compiler doesn't like this, saying of the isDescendantOf essentially that
"this" is const, but is being passed as mutable. However, if I make the
argument const, then the assignment in the loop won't work because unlike
"const (Struct) *", "const (Class)" applies both to the object and the
container.
Is there a way around this aside from recursion?
May 23 2009
Burton Radons wrote:I'm writing an XML class. There are two tests for this class, isAncestorOf and isDescendantOf, that are implemented in terms of one another. They're both const, and look like this: class Node { Node parentNode; /// ... /// Return whether this is an ancestor of the other node. A node is not an ancestor of itself, or of null. bool isAncestorOf (Node node) const { while (node) if ((node = node.parentNode) is this) return true; return false; } /// Return whether one of the parents of this node is the other. A node is not a descendant of itself, or of null. bool isDescendantOf (Node node) const { return node ? node.isAncestorOf (this) : false; } } The compiler doesn't like this, saying of the isDescendantOf essentially that "this" is const, but is being passed as mutable. However, if I make the argument const, then the assignment in the loop won't work because unlike "const (Struct) *", "const (Class)" applies both to the object and the container. Is there a way around this aside from recursion?
std.typecons.rebindable a pointer with a nice wrapper basically. -- My enormous talent is exceeded only by my outrageous laziness. http://www.ssTk.co.uk
May 24 2009








div0 <div0 users.sourceforge.net>