fork(5) download
  1. #include <type_traits>
  2. #include <iostream>
  3.  
  4. template<class C, class T = int>
  5. using EnableIf = typename std::enable_if<C::value, T>::type;
  6.  
  7. template<int N, int M>
  8. struct is_multiple_of : std::integral_constant<bool, N % M == 0>{};
  9.  
  10. template<unsigned I> struct choice : choice<I+1>{};
  11. template<> struct choice<10>{};
  12.  
  13. struct otherwise{ otherwise(...){} };
  14.  
  15. struct select_overload : choice<0>{};
  16.  
  17. template<unsigned N, EnableIf<is_multiple_of<N, 15>>...>
  18. void print_fizzbuzz(choice<0>){ std::cout << "fizzbuzz\n"; }
  19.  
  20. template<unsigned N, EnableIf<is_multiple_of<N, 21>>...>
  21. void print_fizzbuzz(choice<1>){ std::cout << "fizzbeep\n"; }
  22.  
  23. template<unsigned N, EnableIf<is_multiple_of<N, 33>>...>
  24. void print_fizzbuzz(choice<2>){ std::cout << "fizznarf\n"; }
  25.  
  26. template<unsigned N, EnableIf<is_multiple_of<N, 35>>...>
  27. void print_fizzbuzz(choice<3>){ std::cout << "buzzbeep\n"; }
  28.  
  29. template<unsigned N, EnableIf<is_multiple_of<N, 55>>...>
  30. void print_fizzbuzz(choice<4>){ std::cout << "buzznarf\n"; }
  31.  
  32. template<unsigned N, EnableIf<is_multiple_of<N, 77>>...>
  33. void print_fizzbuzz(choice<5>){ std::cout << "beepnarf\n"; }
  34.  
  35. template<unsigned N, EnableIf<is_multiple_of<N, 3>>...>
  36. void print_fizzbuzz(choice<6>){ std::cout << "fizz\n"; }
  37.  
  38. template<unsigned N, EnableIf<is_multiple_of<N, 5>>...>
  39. void print_fizzbuzz(choice<7>){ std::cout << "buzz\n"; }
  40.  
  41. template<unsigned N, EnableIf<is_multiple_of<N, 7>>...>
  42. void print_fizzbuzz(choice<8>){ std::cout << "beep\n"; }
  43.  
  44. template<unsigned N, EnableIf<is_multiple_of<N, 11>>...>
  45. void print_fizzbuzz(choice<9>){ std::cout << "narf\n"; }
  46.  
  47. // we stay with the ellipsis for the general case, so we
  48. // don't have to adjust anything if new overloads are added
  49. template<unsigned N>
  50. void print_fizzbuzz(otherwise){ std::cout << N << "\n"; }
  51.  
  52. template<unsigned N = 1>
  53. void do_fizzbuzz(){
  54. print_fizzbuzz<N>(select_overload{});
  55. do_fizzbuzz<N+1>();
  56. }
  57.  
  58. template<>
  59. void do_fizzbuzz<100>(){
  60. print_fizzbuzz<100>(select_overload{});
  61. }
  62.  
  63. int main(){
  64. do_fizzbuzz();
  65. }
Success #stdin #stdout 0s 2900KB
stdin
Standard input is empty
stdout
1
2
fizz
4
buzz
fizz
beep
8
fizz
buzz
narf
fizz
13
beep
fizzbuzz
16
17
fizz
19
buzz
fizzbeep
narf
23
fizz
buzz
26
fizz
beep
29
fizzbuzz
31
32
fizznarf
34
buzzbeep
fizz
37
38
fizz
buzz
41
fizzbeep
43
narf
fizzbuzz
46
47
fizz
beep
buzz
fizz
52
53
fizz
buzznarf
beep
fizz
58
59
fizzbuzz
61
62
fizzbeep
64
buzz
fizznarf
67
68
fizz
buzzbeep
71
fizz
73
74
fizzbuzz
76
beepnarf
fizz
79
buzz
fizz
82
83
fizzbeep
buzz
86
fizz
narf
89
fizzbuzz
beep
92
fizz
94
buzz
fizz
97
beep
fizznarf
buzz