Templates vs CTFE

Steven Schveighoffer schveiguy at yahoo.com
Fri Jan 7 06:17:42 PST 2011


On Thu, 06 Jan 2011 12:49:19 -0500, Max Samukha <spambox at d-coding.com>  
wrote:

> Some of us who have the knack of writing metaprograms in D know that  
> many algorithms can be implemented with both recursive templates and  
> CTFE. A simple example is map:
>
> Recursive template instantiation:
>
> template staticMap(alias pred, A...)
> {
>      static if (A.length)
>          alias TypeTuple!(pred!(A[0]), staticMap!(A[1..$])) staticMap;
> }
>
> CTFE:
>
> template staticMap(alias pred, A)
> {
>      mixin("alias TypeTuple!(" ~ _staticMap(A.length) ~ ") staticMap;");
> }
>
> private string _staticMap(size_t len)
> {
>      string result;
>      if (len)
>      {
>          result ~= "pred!(A[0])";
>          for(size_t i = 1, i < len; ++i)
>          {
>              result ~= ", pred!(A[" ~ to!string(i) ~ "])";
>          }
>      }
>      return result;
> }
>
> It is not easy to decide which approach to implement in a library  
> because both have drawbacks.
>
> Can anybody give informed advice as to which one is preferable in  
> practice? Or should a library provide both?

You should prefer CTFE IMO.  Templates can leave a trail of instantiated  
templates in the exe.  The compiler does not trim anything out that's only  
used at compile time, but I think with CTFE it does not instantiate as  
many templates.  I'd guess the exe size would be significantly larger for  
the template solution for a large number of elements.

-Steve


More information about the Digitalmars-d mailing list