homer512

FizzBuzz template metaprogramming

May 10th, 2013
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. #include <cstdio>
  2.  
  3. namespace {
  4.   template<int mod3>
  5.   void fizz()
  6.   { /* do nothing */ }
  7.   template<>
  8.   void fizz<0>()
  9.   {
  10.     std::printf("Fizz");
  11.   }
  12.   template<int mod5>
  13.   void buzz()
  14.   { /* do nothing */ }
  15.   template<>
  16.   void buzz<0>()
  17.   {
  18.     std::printf("Buzz");
  19.   }
  20.  
  21.   template<bool mod>
  22.   void decimal(int i)
  23.   {
  24.     std::printf("%d", i);
  25.   }
  26.   template<>
  27.   void decimal<false>(int)
  28.   { /* do nothing */ }
  29.  
  30.   template<int i>
  31.   void loop()
  32.   {
  33.     fizz<i%3>();
  34.     buzz<i%5>();
  35.     decimal<i%3 && i%5>(i);
  36.     std::putchar('\n');
  37.     loop<i+1>();
  38.   }
  39.   template<>
  40.   void loop<101>()
  41.   { /* end recursion */ }
  42. } // namespace
  43. int main()
  44. {
  45.   loop<1>();
  46. }
Advertisement
Add Comment
Please, Sign In to add comment