    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Variadic and Variable Templates</title>
        <link>https://members.accu.org/index.php/articles/2087</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #126 - April 2015</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c348/">o126</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-348/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+348/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Variadic and Variable Templates</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 03 April 2015 20:08:15 +01:00 or Fri, 03 April 2015 20:08:15 +01:00</p>
<p><strong>Summary:</strong>&nbsp;C++11 and 14 offer new features for Variadic and Variable templates. Peter Sommerlad showcases the compile-time possibilities they offer.</p>
<p><strong>Body:</strong>&nbsp;<p>C++11 introduced Variadic Templates and <code>constexpr</code> that ease and allow type-safe computations at compile time. In combination with the C++14 mechanism of Variable Templates, which actually define constants, there are unprecedented possibilities for compile-time computations.</p>

<p>This article not only shows the mechanisms available but also demonstrates a non-trivial example, how they can be used to compute interesting data at compile time to be put into ROM on an embedded device, for example.</p>

<h2>Introduction</h2>

<p>C++ templates have allowed compile-time meta-programming for some time now. However, with C++03 many interesting applications require herculean efforts to achieve results using class-template specializations and function template overloads with variable number of template arguments. Getting such code using variable number of template arguments right is very tedious in the C++03 landscape and even a tiny mistake can produce horrific compiler error messages which are hard to trace back to the origin of the error. Any user of some of the Boost libraries that make heavy use of template meta-programming, such as <code>boost::spirit</code> or <code>boost::mpl</code> can sing that song. [<a href="#[Boost]">Boost</a>]</p>

<p>However, the variadic templates introduced with C++11 make things much more comfortable at the language level. <code>&lt;type_traits&gt;</code> for meta programming were even further improved in C++14. In addition to many more traits, C++14 introduced template aliases for each trait with a suffix <code>_t</code> that allow us to rid the template code of many uses of the <code>typename</code> keyword when working with traits. Also new with C++14 come variadic lambdas, that allow us to use <code>auto</code> as the type for a lambdaâ€™s parameters, so that their type can be deduced from the calling context of the lambda. Another recent change are the relaxed rules for type deduction, so that lambdas and <code>auto</code> return type functions can be specified without a trailing return type, even in the case of multiple return statements. It is only when multiple returned expressions differ in their type that one needs to specify a return type explicitly.</p>

<p>In addition to increased possibilities with lambdas and return type deduction, many of the limitations on C++11 <code>constexpr</code> functions have also been relaxed. In the future, you might see many uses of â€˜<code>constexpr auto</code>â€™ functions that do interesting compile-time computations. Some are shown later.</p>

<p>Finally, variable templates, which are actually parameterized compile-time constants, make the concept of templates more symmetric across the language. </p>

<p>As a library component, <code>std::tuple</code> extends the idea of <code>std::pair</code> to arbitrary collection of values of arbitrary types and <code>std::integer_sequence</code> eases the writing of  code employing such lists of values. </p>

<p>With so much stuff, you might ask, how does that help a â€˜normalâ€™ programmer and how should I employ these. The rest of this article will show you some applications that are useful in day-to-day work or for embedded code employing modern compilers.</p>

<h2>Variadic templates with typename parameters (C++11) </h2>

<p>Whoever has been bitten by the lack of type-safety of <code>printf()</code> might employ a variadic template solution to create a type-safe <code>println</code> function. Recursion is the key to defining successful variadic template functions and makes using classical <code>...</code> varargs parameters in C++ mostly obsolete. (See Listing 1.)</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#ifndef PRINTLN_H_
#define PRINTLN_H_
#include &lt;ostream&gt;
// base case overload
void println(std::ostream &amp;out){
  out &lt;&lt;'\n';
}
// variadic template
template &lt;typename HEAD, typename ... T&gt;
void println(std::ostream &amp; out,HEAD const &amp;h, T const &amp; ... tail){
  out &lt;&lt; h; // cut off head
  if (sizeof...(tail)){
    out &lt;&lt;&quot;, &quot;;
  }
  println(out,tail...); // recurse on tail...
}

#endif /* PRINTLN_H_ */
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>A variadic template introduces a so-called â€˜template parameter packâ€™ by placing three dots (ellipsis) after the typename parameter introduction.  Using the template parameter packâ€™s name (<code>T</code>) to define a function parameter creates a parameter pack (<code>tail</code>). The name of the parameter pack (<code>tail</code>) can later be used within the template to denote a so-called pack-expansion, where the three dots are placed after an expression using the parameter pack name. The corresponding expression is then repeated for each concrete argument. In our <code>println</code> example, even while the base case is not really called, an empty <code>tail</code> (<code>sizeof...(tail)==0</code>) would not call <code>println()</code>, it is necessary to make the code compile. As you might have guessed the <code>sizeof...</code> operator gives the number of elements in a parameter pack. It is also applicable on a template parameter pack name.</p>

<h2>Variable templates basics (C++14)</h2>

<p>In C++, it has always been possible to define constants that were dependent on template arguments using static data members of a class template. To make the language with respect to templates more symmetric and for constants depending on template arguments, C++14 introduced variable templates, which can even be variadic, by the way.</p>

<p>The canonical example from the C++ standard [<a href="#[ISO/IEC]">ISO/IEC</a>] is the definition of pi for any kind of numerical type that looks like the following: </p>

<pre class="programlisting">
  template&lt;typename T&gt; constexpr T pi 
    = T(3.1415926535897932384626433L);</pre>

<p>This allows <code>pi&lt;float&gt;</code> or <code>pi&lt;double&gt;</code> to be computed at compile time and used as such without casting the value. Note that the number of digits given as a long double value are sufficient up to the precision long double allows on todayâ€™s platforms. You can even write <code>pi&lt;complex&lt;double&gt;&gt;</code> to obtain the complex constant with pi as the real part. </p>

<p>If you ever need to calculate with a full circle <code>two_pi</code> might also be defined accordingly: </p>

<pre class="programlisting">
  template&lt;typename T&gt; constexpr T two_pi
    =pi&lt;T&gt;+pi&lt;T&gt;;</pre>

<p>While the example of Pi might not be very impressive, take a look at the examples given later, where whole table computations are hidden behind the initialization of a template variable.</p>

<p>As a more interesting helper, we implement the conversion of degrees to radian values at compile time, using our <code>pi&lt;T&gt;</code> constant. Because degrees, minutes and seconds can be given as integral values, we can implement that using a variable template as well: </p>

<pre class="programlisting">
  template &lt;short degrees, short minutes=0,
    short seconds=0&gt;
  constexpr long double
  rad{(degrees+minutes/60.0L+seconds/3600.0L)
    *pi&lt;long double&gt;/180.0L};

  static_assert(pi&lt;long double&gt;/2 == rad&lt;90&gt;,
    &quot;90 degrees are pi half&quot;); // test it
</pre>

<h2>Variadic templates with non-type parameters and std::integer_sequence (C++11/14)</h2>

<p>In addition to typename parameter packs, C++11 and later also allow parameter packs of non-type template parameters. The usual restrictions on non-type template parameters apply and all arguments of a non-type template parameter pack have to have the same type.</p>

<p>C++14 introduced <code>std::integer_sequence&lt;typename T,T ... elts&gt;</code> to represent such sequences of integers or indices with <code>std::index_sequence&lt;size_t ...&gt;</code> as different types at compile time. A companion factory function <code>make_index_sequence&lt;size_t n&gt;()</code> creates an <code>index_sequence</code> with the numbers up to <code>n</code>.</p>

<p>The following example shows how such an <code>index_sequence</code> can be used to create a <code>std::array</code> with <code>n</code> elements of type <code>size_t</code> is initialized-potentially at compile time-with multiples of parameter <code>row</code> (1 to n times): </p>

<pre class="programlisting">
  template &lt;size_t...I&gt;
  constexpr auto
  make_compile_time_sequence(size_t const row,
     std::index_sequence&lt;I...&gt;){
    return std::array&lt;size_t,sizeof...(I)&gt;{
      {row*(1+I)...}};
  }
  constexpr auto
     array_1_20=make_compile_time_sequence(1,
     std::make_index_sequence&lt;20&gt;{});</pre>

<p>Please excuse the complication of the additional parameter row, but you will see later that we will use that to construct different rows of a multiplication table. For example, <code>make_compile_time_sequence10,std::make_index_sequence&lt;10&gt;{})</code> will create an array with the values 10, 20, 30,... 100. That will be the last row in a multiplication table from 1 times 1 up to 10 times 10.</p>

<p>While it is quite easy to convert the parameter pack to values, using pack-expansion, it is impossible to use a function parameter as a template argument within a <code>constexpr</code> function. This hurdle makes some applications a bit of a burden. However, as the rules for <code>constexpr</code> functions are also relaxed, there is less need for such variadic template machinery to ensure compile-time computation of tables.</p>

<p>As a-slightly unnecessary-complicated example the following code shows how to compute a multiplication table at compile time.</p>

<pre class="programlisting">
  template &lt;size_t...I&gt;
  constexpr
  auto make_compile_time_square
    (std::index_sequence&lt;I...&gt; ){
      return std::array&lt;std::array&lt;size_t,
        sizeof...(I)&gt;,sizeof...(I)&gt;
             {{make_compile_time_sequence(1+I,
               std::make_index_sequence
               &lt;sizeof...(I)&gt;{})...}};
  }</pre>

<p>The pack expansion actually will generate a row in the table for each value the parameter pack I takes. With that, we can create a complete multiplication table from 1*1 to 20*20 with just a single declaration in the 2-dimensional array constant <code>multab_20</code> at compile time:</p>

<pre class="programlisting">
  constexpr auto multab_20 =
     make_compile_time_square(
     std::make_index_sequence&lt;20&gt;{});</pre>

<p>The corresponding test code will output the multiplication table from the constant <code>multab_20</code> (see Listing 2). I even implemented a version that uses <code>std::integer_sequence&lt;char,char ...&gt;</code> to create the multiplication table as a string constant at compile time. But the code is not as nice as I would like it to be. There is work on the way to ease compile-time string processing in a similar way and a means (already implemented by g++ and clang) to create a <code>char_sequence&lt;char ...&gt;</code> from a regular string literal using a user-defined literal template operator that might be standardized for C++17.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
void testCompileTimeArray(std::ostream &amp;out){
  using namespace std;
  for_each(begin(multab_20),end(multab_20),
           [&amp;out](auto row){
    out &lt;&lt; '\n';
    for_each(begin(row),end(row),[&amp;out](auto elt){
      out &lt;&lt; setw(4) &lt;&lt; elt;
    });
  });
  out &lt;&lt; '\n';
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<h2>More â€˜ROMableâ€™ data </h2>

<p>Let us conclude with an example of a compile-time computed table of sine values to enable a quick lookup-and-interpolation-based implementation of a sine function for an embedded system. </p>

<p>To build such a table, we first need a compile-time constexpr version of <code>std::sin(double)</code>. This can be implemented using a Tailor-series that converges quickly [<a href="#[Wikipedia]">Wikipedia</a>]. It can be used independently from the table to create individual sine values at compile time. A run-time use is not recommended, because it will definitely be inferior to <code>std::sin(x)</code>.</p>

<p>The code starts first with some scaffolding to implement the tailor series development of the sine value of x. (See Listing 3.)</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
// sin(x) = sum (-1)^n*(x^(2*n+1))/(2n+1)!
namespace tailor {
template&lt;typename T&gt;
constexpr T pi = T(3.1415926535897932384626433L);
namespace detail{
constexpr long double fak(size_t n) {
  long double res = 1;
  for (size_t i = 2; i &lt;= n; ++i) {
    res *= i;
  }
  return res;
}

constexpr long double sin_denominator
   (long double x, size_t n) {
  long double res{ x }; // 1 + 2n
  for (size_t i = 0; i &lt; n + n; ++i) { 
    // naive, could be log(n), but n&lt;20
    res *= x;
  }
  return res;
}

template&lt;typename T&gt;
constexpr T two_pi =2.0l*pi&lt;T&gt;;

constexpr
long double adjust_to_two_pi(long double x) {
  while (x &gt; two_pi&lt;long double&gt; ) {
    x -= two_pi&lt;long double&gt;;
  } // very naive... not for run-time use
  while (x &lt; -two_pi&lt;long double&gt; ) {
    x += two_pi&lt;long double&gt;;
  }
  return x;
}
} // detail
constexpr long double sin(long double x) {
  long double res = 0;
  x = detail::adjust_to_two_pi(x); // ensures
                                   // convergence
  for (size_t n = 0; n &lt;= 16; ++n) {
    long double const summand
    {detail::sin_denominator(x, n) 
     / detail::fak(2 * n + 1)};
    res += n % 2 ? -summand : summand;
  }
  return res;
}
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p>With that quite slow <code>sin()</code> function in place we can start implementing more. Using the tricks we learned from our multiplication table we can now implement a compile-time lookup table for the sine values for each degree from 0..360 as in Listing 4.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
namespace tables {
template &lt;typename T, size_t ...indices&gt;
constexpr auto
make_sine_table_impl
  (std::index_sequence&lt;indices...&gt;){
  static_assert(sizeof...(indices)&gt;1,
      &quot;must have 2 values to interpolate&quot;);
  return std::array&lt;T,sizeof...(indices)&gt;{{
    sin(indices*two_pi&lt;T&gt;
    /(sizeof...(indices)-1))...
  }};
}
template &lt;size_t n, typename T=long double&gt;
constexpr auto make_sine_table=
    make_sine_table_impl&lt;T&gt;
    (std::make_index_sequence&lt;n&gt;{});
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<p>Listing 5 contains some compile-time tests of our sine table to show that the table is really ROMable using only 5 values.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
constexpr auto testsinetab=tables::make_sine_table&lt;5,long double&gt;;
static_assert(testsinetab[0]==0.0, &quot;sine 0 is 0&quot;);
static_assert(abs(testsinetab[2])&lt;1e-10, &quot;sine pi is 0&quot;);
static_assert(abs(testsinetab.back()) &lt;1e-10, &quot;sine two pi is 0&quot;);
static_assert(abs(testsinetab[1]-1.0)&lt;1e-10, &quot;sine pi/2 is 1&quot;);
static_assert(abs(testsinetab[3]+1.0)&lt;1e-10, &quot;sine pi+pi/2 is -1&quot;);
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<p>And Listing 6 is our compile-time table from 0 to 360 degrees of a circle.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
constexpr auto largesinetab
  =tables::make_sine_table&lt;360+1,double&gt;;
// limited to 1 entry per degree,
// if not giving compiler argument:
//   -fconstexpr-steps=larger

// check it:
static_assert(largesinetab.front()==0,
  &quot;sine 0 is 0&quot;);
static_assert(abs(largesinetab.back())
  &lt;1e-12,&quot;sine 2 pi is 0&quot;);
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 6</td>
	</tr>
</table>

<h2>What is still missing from the standard</h2>

<p>As of C++14 many standard library functions and some types are not yet as compile-time usage friendly. For example, <code>std::array</code> is a literal type, but it can not be incrementally constructed in a <code>constexpr</code> function. A replacement for the time being is cloning <code>std::array</code> and adding <code>constexpr</code> to all member functions. The keyword <code>constexpr</code> was only added to the <code>const</code>-member functions, because these were the only useful positions with C++11â€™s restrictions and nobody recognized the usefulness for C++14 of also having the non-<code>const</code> member functions declared as <code>constexpr</code>.</p>

<p>Also, the standard libraryâ€™s non-modifying algorithms and may be even some of the modifying algorithms could be used in more elaborate <code>constexpr</code> functions, if they would be declared as <code>constexpr</code>. However, there is some tension, since some algorithms might be more efficiently implemented as run-time versions where the limitations of <code>constexpr</code> donâ€™t apply.</p>

<p>A final missing piece are string literals and compile time computation of string values. Work has started on these things and you should expect corresponding compiler and library support for the next standard C++17 making compile time computation still more powerful, allowing even more ROMable data being computed in C++ at compile time.</p>

<p>However, interpreting C++ at compile time is slowing your compiles, and current compilers (clang, g++) will give a strict limit to the number of computations allowed, so to be able to detect endless recursion or endless loops. These limits usually allow for a compile time of single file to be within a minute or a couple of minutes and it can be easily reached. For example, I can create my sine table for 360 degrees, but not per minute or a quarter of a degree, because of the default compiler limits, and even then the compile time is clearly recognizable. You donâ€™t want to include such a header in more than one compilation unit, otherwise we get compile times in days rather than minutes.</p>

<p>So compile-time <code>constexpr</code> computation is a powerful tool in modern C++ to create ROMable data and relieve small processors from the burden of some computation at run time. But it is also a potentially expensive thing that might slow your development, if you try too complicated things at compile time giving people again a reason to complain how slow C++ compiles. But as of today, that wonâ€™t be only the fault of the compiler, but of the developer pushing it to its limits. So use this powerful feature wisely. </p>

<p>Nevertheless, learn how to use variadic templates, since these are reasonable and can simplify template code significantly, especially in a cases where youâ€™d like to use template template parameters, but that might be a story for a future article.</p>

<h2>References</h2>

<p class="bibliomixed"><a id="[Boost]"></a>[Boost] Boost Libraries, <a href="http://www.boost.org">http://www.boost.org;</a></p>

<ul>
	<li><a href="http://www.boost.org/doc/libs/1_57_0/libs/spirit/doc/html/index.html">Boost Spirit, http://www.boost.org/doc/libs/1_57_0/libs/spirit/doc/html/index.html;</a></li>
	
	<li>Boost MPL, <a href="http://www.boost.org/doc/libs/1_57_0/libs/mpl/doc/index.html">http://www.boost.org/doc/libs/1_57_0/libs/mpl/doc/index.html</a>;</li>
</ul>
<p>both  accessed April 5th 2015</p>

<p class="bibliomixed"><a id="[ISO/IEC]"></a>[ISO/IEC] <em>ISO/IEC International Standard 14882</em>, Fourth edition 2014-12-15, Information technology â€“ Programming languages â€“ C++</p>

<p class="bibliomixed"><a id="[Wikipedia]"></a>[Wikipedia] Sine Tailor Series definition; Wikipedia, <a href="http://en.wikipedia.org/wiki/Sine#Series_definition">http://en.wikipedia.org/wiki/Sine#Series_definition</a>, accessed December 1st 2014</p>

<h3>Example source code</h3>

<p>The example source code is available on Github: <a href="https://github.com/PeterSommerlad/Publications/tree/master/ACCU/variadic_variable_templates">https://github.com/PeterSommerlad/Publications/tree/master/ACCU/variadic_variable_templates</a></p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
