I am writing an unshakable binary tree class in which all methods (Insert, Remove, RotateLeft, etc.) return a new instance of the tree instead of changing it.
I am going to create many different tree implementations: Avl tree, red-black tree, splay tree, etc. I have the following:
public class AbstractBinaryTree<TreeType, T> where TreeType : AbstractBinaryTree<TreeType, T> where T : IComparable<T> { protected abstract TreeType CreateNode(TreeType left, T value, TreeType right); protected abstract T Value { get; } protected abstract TreeType Left { get; } protected abstract TreeType Right { get; } protected abstract bool IsNil(); public TreeType Insert(T item) { if (this.IsNil()) { return CreateNode(this, item, this);
The idea here is that AbstractBinaryTree is a node tree - moreover, it is the same type as TreeType . If I can use the above base class correctly, I can write something like this:
public class AvlTree<T> : AbstractBinaryTree<AvlTree<T>, T> { public override AvlTree<T> Insert(T item) { return Balance(base.Insert(item)); } }
so that my Insert method returns AvlTree<T> instead of AbstractBinaryTree<AvlTree<T>, T> . However, I cannot even get this far, because the base class does not compile.
How to pass an instance of AbstractBinaryTree to a method that accepts a TreeType type?
source share