Imperative templates

Robert Clipsham robert at octarineparrot.com
Sat Jul 16 08:58:25 PDT 2011


So in several presentations given about D that I've seen there's a list 
of supported paradigms given which looks something like this:

  - Imperative
  - Metal
  - Object-oriented
  - RAII
  - Functional
  - Generic
  - Generative
  - Concurrent

(That list from 
http://assets.en.oreilly.com/1/event/45/The%20D%20Programming%20Language%20Presentation.pdf 
). But if this is the case, why do we not get this choice for template 
programming?

Currently templates have to be written in a functional manner, which is 
incredibly difficult if you're used to imperative programming, and I've 
found the code that it leads to is really difficult to maintain, even if 
it's well commented (this may not be the case for folk that are well 
versed in functional programming).

What I'd like to suggest is something like this:
----
/// Template to get every other type in a type tuple
template AlternateEven(T...)
{
     enum U = TypeTuple!();
     for (size_t i = 0; i < T.length; i++)
     {
         if ((i & 1) == 0)
         {
             U ~= T[i];
         }
     }
     alias U AlternateEven;
}
----

To do this currently you need something like:
----
template AlternateEven(T...)
{
     alias AlternateEvenImpl!(0, T) AlternateEven;
}

template AlternateEvenImpl(size_t i, T...) if ((i & 1) == 0)
{
     static if (i < T.length)
     {
         alias TypeTuple!(T[i], AlternateEvenImpl!(i + 1, T)) 
AlternateEvenImpl;
     }
     else
     {
         alias TypeTuple!() AlternateEvenImpl;
     }
}

template AlternateEvenImpl(size_t i, T...) if ((i & 1) != 0)
{
     static if (i < T.length)
     {
         alias AlternateEvenImpl!(i + 1, T) AlternateEvenImpl;
     }
     else
     {
         alias TypeTuple!() AlternateEvenImpl;
     }
}
----

Which is a lot more code, and a lot harder to understand at a quick 
glance. It gets even worse if you want to do something more 
complicated[1][2].

I don't think my example is the best example for a possible syntax, but 
that could be worked on. What does anyone else think?

[1] https://github.com/mrmonday/dmd/blob/js/dsrc/bind/util.d#L134
[2] 
https://github.com/mrmonday/serenity/blob/master/serenity/persister/Sqlite.d#L126

-- 
Robert
http://octarineparrot.com/


More information about the Digitalmars-d mailing list