Painful Generics, Operator '> =' cannot be applied to operands of type T and T,

Here is my code:

class BinaryTree<T> { private node<T> Head; public class node<T> { public T Data; public node<T> right; public node<T> left; public node<T> parent; ... } ... private void insert(ref T data, node<T> parent, ref node<T> currentChild) { ... { if (currentChild.Data >= data) insert(ref data, currentChild, ref currentChild.right); else insert(ref data, currentChild, ref currentChild.left); } } } 

Above, at the point if (currentChild.Data >= data) , an error appears:

The operator '> =' cannot be applied to operands of type 'T' and 'T'

What do I need to do to fix the error?

+6
source share
6 answers

The classic solutions to this problem are: (1) make T IComparable<T> or (2) use IComparer<T> or a functor for your class.

(1)

 class BinaryTree<T> where T : Comparable<T> ... 

(2)

 class BinaryTree<T> { private node<T> Head; private readonly IComparer<T> comparer; public BinaryTree(IComparer<T> comparer) { this.comparer = comparer; } //... } 
+8
source

You need to indicate that T implements IComparable so you can compare:

 class BinaryTree<T> where T : IComparable<T> { ... public class node<T> where T : IComparable<T> ... ... if (currentChild.Data.CompareTo(data) >= 0) ... ... } 
+10
source

I do not know about C #, but in Java you will need to have an instance of the generic Comparator class parameterized with the types you want to compare. This generic class provided a compareTo () function that would be implemented in such a way as to allow two types to be compared.

+1
source

T must be a type that implements IComparable, and then use its comparison with the method instead of> =. Operator overloading is another option if you still want to support> =.

+1
source

While some people suggest using IComparable, I would suggest using IComparer<T> instead, which should be stored in the field of your tree. One of the constructors of your tree should accept IComparer<T> , which should be stored in your field. The other should probably set the IComparer<T> field to Comparer<T>.InvariantDefault() . Thus, the consumers of your tree will be able to choose how things will be sorted in the tree. Note that if IComparer<T> provided when building the class, there is no real reason that T would have to implement IComparable<T> . It might be nice to provide a compile-time requirement T implement IComparer<T> when building a tree without specifying a comparison method, but there is no way to do this without requiring some inconvenient syntax such as treeInstance = factoryClass.Create<myType>() that created would be an instance of treeClass<myType> .

+1
source

I assume that the data is of type Object and thus does not automatically allow the> = operation. You need to add a constraint for T so that it is IComparable

 class BinaryTree<T> where T : IComparable 
0
source

Source: https://habr.com/ru/post/906841/


All Articles