Applying const to an object but not the container (D 2.0)

div0 div0 at users.sourceforge.net
Sun May 24 13:15:13 PDT 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


More information about the Digitalmars-d-learn mailing list