Template design with required type parameters?

Benji Smith dlanguage at benjismith.net
Sun Nov 12 14:01:17 PST 2006


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



More information about the Digitalmars-d-learn mailing list