This is a challenge for the C# generics / design patterns masters.
I’m trying to implement a generic heap, and then a priority queue that uses the heap.
My heap’s signature is:
class Heap<TKey, TValue> where TKey : IComparable<TKey>
My priority queue class is:
public delegate IComparable<T> Evaluator<T>(T item);
class PriorityQueue<T> : IQueue<T>
{
Evaluator<T> Evaluate;
Heap<IComparable<T>, T> m_heap;
public PriorityQueue(Evaluator<T> evaluateFunction)
{
Evaluate = evaluateFunction;
m_heap = new Heap<int, T>(HeapType.MinHeap);
}
...
public void Insert(T element)
{
m_heap.Insert(Evaluate(element), element);
}
...
But when doing so, the compiler (justifiably) complains that ICompareble doesn’t implement the ICompareble interface, hence
Heap<IComparable<T>, T> m_heap;
conflicts with
where TKey : IComparable<TKey>
What can you do to solve this?!
full compiler error:
The type 'System.IComparable<T>' cannot be used as type parameter 'TKey' in the generic type or method 'Heap<TKey,TValue>'. There is no implicit reference conversion from 'System.IComparable<T>' to 'System.IComparable<System.IComparable<T>>'.
Your implementation is pretty muddled. It seems to me like this is sufficient:
Is there some reason the priority queue should have a generic key? If so, then you should specify
PriorityQueue<TKey, TValue>instead and replaceintwithTKey, adding the constraint thatTKey : IComparable<TKey>(just like in your heap’s signature.)Basically, your priority queue’s definition should either look like your heap’s definition, if you want the key to be of any type, or the same but not parameterized on the key type.