Template design with required type parameters?

JC johnch_atms at hotmail.com
Sat Nov 11 01:57:37 PST 2006


"Benji Smith" <dlanguage at benjismith.net> wrote in message 
news:ej3d54$2k2s$1 at digitaldaemon.com...
> Benji Smith wrote:
>> He was probably thinking something along the lines of the C# construct:
>>
>>   class SortedMap<K, V> where K : IComparable {
>>     // ...
>>   }
>>
>> It looks like the contract & assertion will accomplish the same thing, 
>> though not quite as cleanly as the parametric constraint in C#.

Actually C# sprang to mind when I read the original post. The C# syntax for 
constraints is very succinct, but quite limited.

>>
>> --benji
>
> Oops. Looks like I missed the whole section called 'Template 
> Specialization'.
>
> Silly me :^P

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.");
}

John. 





More information about the Digitalmars-d-learn mailing list