Sunday, March 14, 2010

exploring variadic templates of C++0x

Yesterday I was thiking about how to try using variadic templates.
First thing that came to my mind was to define something 
like binary literals. It can be implemented without any variadic 
templates, but not too general or too verbose: link.
 
Variadic solution looks a bit better. Compilation time is almost
unaffected compared to numeric constant version. Also I had to use
some trickery to make it substitute "tail..." well as described here. 
 
Here is my code.

    1 #include <iostream>
    2 
    3 template <class Num, Num val, int... bitlist>
    4 class binary;
    5 
    6 template <class Num, Num val, int head, int... tail>
    7 class binary<Num, val, head, tail...>
    8 {
    9 public:
   10   static const Num value =
   11     binary<Num, val * 2 + head, tail...>::value;
   12 };
   13 
   14 template <class Num, Num val>
   15 class binary<Num, val> {
   16 public:
   17   static const Num value = val;
   18 };
   19 
   20 int main()
   21 {
   22 
   23   // large positive
   24   unsigned long long k = binary<unsigned long long,
   25     1, 1, 1, 1, 1, 1, 1, 1,
   26     1, 1, 1, 1, 1, 1, 1, 1,
   27     1, 1, 1, 1, 1, 1, 1, 1,
   28     1, 1, 1, 1, 1, 1, 1, 1,
   29     1, 1, 1, 1, 1, 1, 1, 1,
   30     1, 1, 1, 1, 1, 1, 1, 1,
   31     1, 1, 1, 1, 1, 1, 1, 1,
   32     1, 1, 1, 1, 1, 1, 1, 1>::value;
   33   std::cout << "k is " << k << std::endl;
   34 
   35   //small negative:
   36   char c = binary<char, 1, 1, 1, 1, 1, 1, 1, 1>::value;
   37   std::cout << "c is " << (int)c << std::endl;
   38 }

No comments:

Post a Comment