Question about function type parameter type hints?

Ali Çehreli acehreli at yahoo.com
Mon Jul 15 12:23:04 PDT 2013


On 07/15/2013 11:56 AM, Gary Willoughby wrote:

 > class TypeHint
 > {
 >      public T method(T)() if (is(T == int))
 >      {
 >          return T.init;
 >      }
 > }
 >
 > ...
 >
 > class TypeHint
 > {
 >      public T method(T : int)()
 >      {
 >          return T.init;
 >      }
 > }
 >
 > ...

Classes make this question more complicated than it actually is. :) The 
same can be said for non-member functions as well.

 > Are the two above class declarations achieving the same thing? i.e. is
 > the type hint of the second snippet shorthand for the first's 'if'?

They are not the same feature but sometimes they achieve the same purpose.

The former uses a template constraint, communicating to the callers that 
T can only be int. This allows the compiler to generate an error 
message, importantly at the call site. So, it is the responsibility of 
the caller to ensure that method() member function is called by an int.

The latter is a template specialization. (Although, I remember reading 
here that D templates don't have specialization; I don't understand the 
technicalities.) When this form is used, generally I would expect to see 
a non-specialized overload of method() as well. The non-specialized 
would be for all the other types and (T : int) would be for int.

 > If so which is preferred?

When constraining the use, I prefer the former. When defining a special 
implementation for int, I prefer the latter.

Ali



More information about the Digitalmars-d-learn mailing list