www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Question about function type parameter type hints?

reply "Gary Willoughby" <dev nomad.so> writes:
class TypeHint
{
	public T method(T)() if (is(T == int))
	{
		return T.init;
	}
}

...

class TypeHint
{
	public T method(T : int)()
	{
		return T.init;
	}
}

...

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'? If so which is preferred?
Jul 15 2013
next sibling parent "Dicebot" <public dicebot.lv> writes:
On Monday, 15 July 2013 at 18:56:38 UTC, Gary Willoughby wrote:
 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'? If so which is preferred?
No, ":" stands for "same or implicitly convertible" while "==" is strict "same": T foo1(T : int)() { return T.init; } T foo2(T)() if (is(T == int)) { return T.init; } void main() { foo1!short(); foo2!short(); // error } As far as I know there are no "==" syntax for template specialization. Usually template specialization syntax is preferable for simple cases because it is more readable but any complex case pretty much requires "if" constraint.
Jul 15 2013
prev sibling parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
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
Jul 15 2013