Consider what happens if we deviate from CRTP convention by writing...
public class Foo : TreeNode<Foo>
{
}
public class Bar : TreeNode<Foo> // parting from convention
{
}
...and then call the above code as follows:
var foo = new Foo();
var foobar = new Bar();
foobar.AddChild(foo);
The AddChild
call throws an InvalidCastException
saying Unable to cast object of type 'Bar' to type 'Foo'.
Regarding the CRTP idiom - it is convention alone requiring the generic type to be the same as the declaring type. The language must support the other cases where CRTP convention is not followed. Eric Lippert wrote a great blog post on this topic, that he linked from this other crtp via c# answer.
All of that said, if you change the implementation to this...
public class TreeNode<T> where T : TreeNode<T>
{
public void AddChild(T a_node)
{
a_node.SetParent(this);
}
void SetParent(TreeNode<T> a_parent)
{
m_parent = a_parent;
}
TreeNode<T> m_parent;
}
...the above code that previously threw the InvalidCastException
now works. The change makes m_Parent
a type of TreeNode<T>
; making this
either the type T
as in the Foo
class' case or a subclass of TreeNode<T>
in the Bar
class case since Bar
inherits from TreeNode<Foo>
- either way allows us to omit the cast in SetParent
and by that omission avoid the invalid cast exception since the assignment is legal in all cases. The cost of doing this is no longer being able to freely use T
in all places as it had previously been used which sacrifices much of the value of CRTP.
A colleague/friend of mine considers himself a newbie to a language/language-feature until he can honestly say that he's "used it in anger;" that is, he knows the language well enough to be frustrated that there is either no way of accomplishing what he needs or that doing so is painful. This very well could be one of those cases, as there are limitations and differences here that echo the truth that generics are not templates.