daily pastebin goal
61%
SHARE
TWEET

FizzBuzz in C++ templates

chvor Dec 10th, 2011 39 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. template< int x >
  4. struct FizzBuzz
  5. {
  6.         void operator()()
  7.         {
  8.                 std::cout << x << std::endl;
  9.         }
  10. };
  11.  
  12. template<>
  13. struct FizzBuzz<-1>
  14. {
  15.         void operator()()
  16.         {
  17.                 std::cout << "Fizz" << std::endl;
  18.         }
  19. };
  20.  
  21. template<>
  22. struct FizzBuzz<-2>
  23. {
  24.         void operator()()
  25.         {
  26.                 std::cout << "Buzz" << std::endl;
  27.         }
  28. };
  29.  
  30. template<>
  31. struct FizzBuzz<-3>
  32. {
  33.         void operator()()
  34.         {
  35.                 std::cout << "FizzBuzz" << std::endl;
  36.         }
  37. };
  38.  
  39. template< int x >
  40. struct Selector
  41. {
  42.         enum
  43.         {
  44.                 v = ( ( x % 15 ) == 0 ? -3 :
  45.                                 ( x % 5 ) == 0 ? -2 :
  46.                                 ( x % 3 ) == 0 ? -1 : x )
  47.         };
  48. };
  49.  
  50. template< int x >
  51. struct ReverseIter : public ReverseIter< x - 1 >
  52. {
  53.         void operator()()
  54.         {
  55.                 ReverseIter< x - 1 >()();
  56.                 FizzBuzz< Selector< x >::v > f;
  57.                 f();
  58.         }
  59. };
  60.  
  61. template<>
  62. struct ReverseIter< 0 >
  63. {
  64.         void operator()()
  65.         {
  66.         }
  67. };
  68.  
  69. int
  70. main( void )
  71. {
  72.         ReverseIter<100> r;
  73.         r();
  74.         return 0;
  75. }
  76.  
  77.  
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top