default values depending on type of template variable

Ali Çehreli acehreli at yahoo.com
Wed Sep 11 09:05:47 UTC 2019


On 09/11/2019 01:35 AM, berni wrote:
> I'd like to write a template, that takes a different default value 
> depending on the type of a variable.

Like this?

import std.stdio;

void main()
{
   double a = 1e-8;
   double b = 1e-10;
   float c = 1e-4;
   float d = 1e-6;

   assert(!test(a));
   assert(test(b));
   assert(!test(c));
   assert(test(d));
}

template DefaultFor(T) {
   static if (is (T == float)) {
     enum DefaultFor = 1e-5;

   } else static if (is (T == double)) {
     enum DefaultFor = 1e-9;

   } else {
     import std.string;
     static assert (false, format!"%s not supported"(T.stringof));
   }
}

auto test(T, U)(T value, U limit=DefaultFor!T)
{
   writefln!"%s: %s(%s)"(T.stringof, U.stringof, limit);
   return value<limit;
}

Ali


More information about the Digitalmars-d-learn mailing list