Function Arguments with Multiple Types
Bob4
none at gmail.com
Fri Sep 6 20:46:45 UTC 2019
On Friday, 6 September 2019 at 20:16:58 UTC, Ali Çehreli wrote:
> On 09/06/2019 01:02 PM, Bob4 wrote:
>
> > I feel like it's wrong to rewrite identical functions over
> and over.
>
> Enter templates. :)
>
> auto clamp(T)(T value, T mini, T maxi) {
> if (value >= maxi) {
> return maxi;
> }
> if (value <= mini) {
> return mini;
> }
> return value;
> }
>
> unittest {
> assert(clamp("k", "d", "y") == "k");
> assert(clamp(42, 10, 20) == 20);
> assert(clamp(0.5, 1.5, 1_000) == 1.5);
> }
>
> void main() {
> }
>
> You can improve the function with template constraints.
>
> Ali
Thanks; this works, but I'm not sure why. Where does `T` come
from? I notice that I can change it to something else, like
`ABC`, but I'm not sure why I need a `(T)` prepending the
arguments.
What's the best way to type check the variables? I tried to use
prepend `assert(cast(T)value !is null);` to the beginning of the
function, but that didn't work.
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))
{}
```
More information about the Digitalmars-d-learn
mailing list