I'm writing a generic class for min heap where I want to be able to heapify on TKey
as well as T
.
interface IHeap<T, TKey>
where TKey : IComparable<TKey>
{
void Insert(T x);
T Delete();
T Top();
}
public class MinHeap<T, TKey> : IHeap<T, TKey>
where TKey : IComparable<TKey>
{
public MinHeap(int capacity)
: this(capacity, x => x) // <---- compilation error here
{ }
public MinHeap(int capacity, Func<T, TKey> keySelector)
: this(capacity, keySelector, Comparer<TKey>.Default)
{ }
public MinHeap(int capacity, Func<T, TKey> keySelector, IComparer<TKey> comparer)
{
// ...
}
// ...
}
I get these compilation errors for x => x
:
Cannot convert lambda expression to delegate type 'System.Func<T,TKey>' because some of the return types in the block are not implicitly convertible to the delegate return type.
Cannot implicitly convert type 'T' to 'TKey'
How do I achieve this and just have one class?
Update:
I want to be able to do two things:
// 1
var minheap = new MinHeap<Person, int>(10, x => x.Age);
// 2
var minheap = new MinHeap<int>(10);
// instead of
var minheap = new MinHeap<int, int>(10, x => x);
MinHeap<T,TKey>
can be instantiated with any generic type parameters matching the constraints.
That means for example, you could have a MinHeap<string,int>
. In that case, you'd be trying to assign lambda x => x
to a Func<string,int>
which wouldn't work, since it's a Func<string,string>
.
I don't think there is a sensible way to achieve what you want, as there's no good candidate for a "default" way to convert one arbitrary type to another arbitrary type, which is what you'd need.
What you could do is remove this constructor and add a static constructor which could be used for the cases when the T
and TKey
are the same type:
public static class MinHeap
{
public static MinHeap<T,T> Create<T>(int capacity) where T : IComparable<T>
{
return new MinHeap<T,T>(capacity, x => x);
}
}
But if this isn't enough for your needs, then just remove the constructor and accept that people will have to deal with passing a lambda in themselves.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments