Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

generics

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 point if (currentChild.Data >= data) I am getting error :

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

What do I do to resolve the error?

like image 530
Mr.Anubis Avatar asked Jan 25 '12 10:01

Mr.Anubis


4 Answers

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

class BinaryTree<T> where T : IComparable<T>
{
    ...
    public class node<T> where T : IComparable<T> ...
    ...
    if (currentChild.Data.CompareTo(data) >= 0) ...
    ...
}
like image 95
Petar Ivanov Avatar answered Nov 12 '22 07:11

Petar Ivanov


The classic solutions to this problem are (1) to make T IComparable<T>, or (2) to use an IComparer<T> or a functor to 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;
    }
    //...
}
like image 8
Sergey Kalinichenko Avatar answered Nov 12 '22 07:11

Sergey Kalinichenko


I don't know about C#, but in Java you would need to have an instance of a generic Comparator class, parametrized with the types you want to compare. This generic class provided a compareTo() function which would be implemented in a way that allows for comparison of the two types.

like image 1
Daniel Kamil Kozar Avatar answered Nov 12 '22 05:11

Daniel Kamil Kozar


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

like image 1
chandmk Avatar answered Nov 12 '22 05:11

chandmk