Function Arguments with Multiple Types

Ali Çehreli acehreli at yahoo.com
Fri Sep 6 21:02:31 UTC 2019


On 09/06/2019 01:46 PM, Bob4 wrote:

 > Thanks; this works, but I'm not sure why. Where does `T` come from?

Well... I assumed this would make you research templates. ;) Here is one 
resource: http://ddili.org/ders/d.en/templates.html

(T) means "this function is for any type; and I call that type T in the 
implementation."

 > notice that I can change it to something else, like `ABC`, but I'm not
 > sure why I need a `(T)` prepending the arguments.

Templates have two parameter lists; the compile-time parameter list 
comes first. You can call type parameters anything that makes sense; T 
is very common.

 > What's the best way to type check the variables?

With template constraints: 
http://ddili.org/ders/d.en/templates_more.html#ix_templates_more.constraint,%20template

 > I tried to use prepend
 > `assert(cast(T)value !is null);` to the beginning of the function, but
 > that didn't work.

That would bring an implicit requirement to your template: The type 
would have to be usable with the !is operator. (Template constraints 
make such requirements explicit.)

 > I tried this, too, but it didn't work either (in fact it seemed to
 > ignore it entirely when I replaced `T` with this):
 >
 > ```
 > template Number(T)
 >      if (is(T == float))
 > {}
 > ```

That should work, meaning "enable this template only if T is 'float'" 
(which would defeat the purpose of a template but I understand that it's 
a test.)

Ali



More information about the Digitalmars-d-learn mailing list