Template design with required type parameters?

JC johnch_atms at hotmail.com
Sun Nov 12 15:27:27 PST 2006


"Benji Smith" <dlanguage at benjismith.net> wrote in message 
news:ej85jd$ut3$1 at digitaldaemon.com...
> One thing in C# that drives me nuts is that you can't do comparisons on 
> primitive values without boxing and unboxing them and using IComparer 
> objects.
>
> >  class BubbleSorter<T> {
> >
> >    T[] items;
> >
> >    public BubbleSorter(T[] items) {
> >      this.items = items;
> >    }
> >
> >    public T[] sort() {
> >      bool needsMoreSorting = true;
> >      while (needsMoreSorting) {
> >        needsMoreSorting = false;
> >        for (int i = 1; i < items.Count; i++) {
> >          int prevIndex = i - 1;
> >
> >          // COMPILE ERROR! You can't use comparison operators with
> >          // generic parameters. You must use an IComparer<T> instead.
> >
> >          if (items[prevIndex] > items[i]) {
> >            swap(items, prevIndex, i);
> >            needsMoreSorting = true;
> >          }
> >
> >        }
> >      }
> >      return items;
> >    }
> >  }
>
> You can fix this by using something like the following:
>
> >  class BubbleSorter<T> where T : IComparable {
> >    // ...
> >  }
>
> ...and then using an IComparer to compare values (instead of the < or > 
> operators). But then you incur the speed penalty of boxing/unboxing, not 
> the mention the relatively high cost of the comparator method call.

Actually, if you use Comparer<T>.Default, and T implements IComparable<T>, 
you get a Comparer object specialised for that type which avoids boxing and 
unboxing.

>
> Being able to constrain a template like this would be ideal:
>
> >  class BubbleSorter<T> where T implements opCmp {
> >    // ...
> >  }
>
> Or something like that.
>
> --benji 





More information about the Digitalmars-d-learn mailing list