template parameters

Ali Çehreli acehreli at yahoo.com
Mon Aug 30 00:05:06 UTC 2021


On 8/29/21 3:31 PM, Charles Hixson wrote:
 > Thanks.  I going to have to study:
 >
 > enum supportsCall = isIntegral!(typeof(T.init.%s()));
 >
 >
 > for awhile to make any sense of that, but it looks like just what I was
 > looking for.

Trying to explain with comments:

// This is an eponymous template because it contains
// a symbol that's the same as the name of this template.
// And that symbol is 'supportsCall'. So, this template
// will be whatever that symbol is. (In this case, it
// will be a compile-time know entity: 'enum bool'.)

template supportsCall(T, string func) {
   import std.format : format;
   import std.traits : isIntegral;

   // This is a string expression we will mix-in below.
   enum expr = format!q{
     enum supportsCall = isIntegral!(typeof(T.init.%s()));
   }(func);

   // The above expression will be the following e.g.
   // for 'int' and for "ndx":
   //
   //   enum supportsCall = isIntegral!(typeof(int.init.ndx()));
   //
   // So, it's determining whether the typeof the expression
   // int.init.ndx() is an integral.
   //
   // 'supportsCall' is a bool, which I could have made explicit:
   //
   //   enum bool supportsCall = [...]
   //
   // You can prove it for yourself by "printing" the expression
   // at compile time:

   pragma(msg, expr);

   // Here is where we mix-in the expression into this template's
   // definition.

   mixin (expr);
}

Then the whole template can be used as a compile-time bool value.

Ali



More information about the Digitalmars-d-learn mailing list