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

Burton Radons burton.radons at gmail.com
Sat May 23 09:14:44 PDT 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?


More information about the Digitalmars-d-learn mailing list