Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Intrusive tree structure, using CRTP

Tags:

c#

tree

crtp

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...

like image 552
s0ubap Avatar asked Oct 09 '22 15:10

s0ubap


2 Answers

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'
like image 149
usr Avatar answered Oct 11 '22 05:10

usr


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>.

like image 27
CodesInChaos Avatar answered Oct 11 '22 04:10

CodesInChaos