I'm currently working on a simple way to implement a intrusive tree structure in C#. As I'm mainly a C++ programmer, I immediatly wanted to use CRTP. Here is my code:
public class TreeNode<T> where T : TreeNode<T>
{
public void AddChild(T a_node)
{
a_node.SetParent((T)this); // This is the part I hate
}
void SetParent(T a_parent)
{
m_parent = a_parent;
}
T m_parent;
}
This works but... I can't understand why I have to cast when calling a_node.SetParent((T)this), as I'm using generic type restriction... C# cast has a cost, and I'd like not to spread this cast in each intrusive collection implementation...
this is at least of type TreeNode. It could be derived or it could be exactly TreeNode. SetParent expects a T. But T can be a different type than this is of. We know that this and T both derive from TreeNode but they can be different types.
Example:
class A : TreeNode<A> { }
new TreeNode<A>() //'this' is of type 'TreeNode<A>' but required is type 'A'
Nobody guaranteed that T
and the type of this
are the same. They can even be unrelated subclasses of TreeNode
.
You expect T
to be used in the curiously recurring template pattern, but generic constraints can't express that.
A stupid implementation could be defined as StupidNode:TreeNode<OtherNode>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With