Function Arguments with Multiple Types

Ali Çehreli acehreli at yahoo.com
Fri Sep 6 20:16:58 UTC 2019


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



More information about the Digitalmars-d-learn mailing list