Template design with required type parameters?

Charles D Hixson charleshixsn at earthlink.net
Thu Nov 16 16:03:16 PST 2006


Benji Smith wrote:
> JC wrote:
>> Specialization is fine for constraining to one type. Type checking is 
>> much more flexible. For example, you can check that a type has a 
>> certain method, or operator like opAdd (though this doesn't work on 
>> basic types).
>>
>> Also, specializations don't appear to allow you to constrain to enum, 
>> struct, class, interface, union, delegate and function, whereas 
>> IsExpressions do.
>>
>> void onlyForEnums(T : enum)(T e) { // error: found 'enum' when 
>> expecting ')'
>> }
>>
>> void onlyForEnums(T)(T e) {
>>   static if (!is(T : enum)) static assert(false, "Type not an enum.");
>> }
> 
> Excellent points.
> 
> 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.
> 
> Being able to constrain a template like this would be ideal:
> 
>  >  class BubbleSorter<T> where T implements opCmp {
>  >    // ...
>  >  }
> 
> Or something like that.
> 
> --benji
Yes, that's what I meant.  I take it that one can do:
class BubbleSorter<T> where T : IComparable {
but not:
class BubbleSorter<T> where T implements opCmp {

(The second would be nicer in general, but I was really asking 
about the first.  I can define an interface to contain just 
the functions that I need to have matched.)

Thanks to all!
(I missed the section on Template Specialization also.)



More information about the Digitalmars-d-learn mailing list