Want more features on Pastebin? Sign Up, it's FREE!
Guest

CT FizzBuzz

By: a guest on Apr 25th, 2012  |  syntax: C++  |  size: 1.78 KB  |  views: 33  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <iostream>
  2.  
  3. template <char N>
  4. struct CharToStringHolder
  5. {
  6.   const char data[4];
  7.   constexpr inline CharToStringHolder()
  8.             : data({N / 100 + 48, N / 10 + 48, N % 10 + 48, 0}) {}
  9. };
  10.  
  11. template <char N>
  12. constexpr const char* char_to_string()
  13. {
  14.   return CharToStringHolder<N>().data;
  15. }
  16.  
  17. template <char N>
  18. constexpr const char* fizzbuzz()
  19. {
  20.   return ( ( N % 3 == 0 && N % 5 == 0 ) ? "FizzBuzz"
  21.                      : ( ( N % 3 == 0 ) ? "Fizz"
  22.                      : ( ( N % 5 == 0 ) ? "Buzz"
  23.                      : char_to_string<N>() )));
  24. }
  25.  
  26. template<const char*... args>
  27. struct CompileTimeArray
  28. {
  29.   static const char* data[sizeof...(args)];
  30. };
  31.  
  32. template<const char*... args>
  33. const char* CompileTimeArray<args...>::data[sizeof...(args)] = { args... };
  34.  
  35. template<size_t N, template<size_t> class MetaFunc, const char*... args>
  36. struct generate_array_impl
  37. {
  38.   typedef typename generate_array_impl<N-1, MetaFunc, MetaFunc<N>::value, args...>::result result;
  39. };
  40.  
  41. template<template<size_t> class MetaFunc, const char*... args>
  42. struct generate_array_impl<0, MetaFunc, args...>
  43. {
  44.   typedef CompileTimeArray<MetaFunc<0>::value, args...> result;
  45. };
  46.  
  47. template<size_t N, template<size_t> class MetaFunc>
  48. struct GenerateArray
  49. {
  50.   typedef typename generate_array_impl<N-1, MetaFunc>::result result;
  51. };
  52.  
  53. template<size_t index>
  54. struct FizzBuzzMetaFunc
  55. {
  56.   static const char value[sizeof(fizzbuzz<index>())];
  57. };
  58.  
  59. template<size_t index>
  60. const char FizzBuzzMetaFunc<index>::value[sizeof(fizzbuzz<index>())] = {fizzbuzz<index>()};
  61.  
  62. int main(void)
  63. {
  64.   const size_t count = 100;
  65.   typedef typename GenerateArray<count, FizzBuzzMetaFunc>::result A;
  66.  
  67.   for(size_t i = 0; i < count; ++i)
  68.   {
  69.     std::cout << A::data[i] << "\n";
  70.   }
  71.  
  72.   return 0;
  73. }
clone this paste RAW Paste Data