Skip to content

Instantly share code, notes, and snippets.

@1995eaton
Created May 15, 2015 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1995eaton/48dfbadd257261665ae4 to your computer and use it in GitHub Desktop.
Save 1995eaton/48dfbadd257261665ae4 to your computer and use it in GitHub Desktop.
FizzBuzz with C++ template metaprogramming
/*
g++ -std=c++14 -ftemplate-depth=2001 fizz.cc -o fizz 2>&1 >/dev/null | grep -oE '[0-9]+, (Fizz|Buzz|FizzBuzz|None)'
*/
#include <iostream>
struct Fizz;
struct Buzz;
struct FizzBuzz;
struct None;
// Overflows if test passes: spits out the number
// n, and one of Fizz, Buzz, FizzBuzz, or None
// on the same line.
template <bool test, int n, typename T>
struct print {
static constexpr char value = test + 255;
};
template <int i, int n=1> struct fizzbuzz {
static constexpr int test =
n % 15 == 0 ? 15 :
n % 3 == 0 ? 3 :
n % 5 == 0 ? 5 : 0;
static constexpr auto value =
fizzbuzz<(i - 1), (n + 1)>::value +
print<test == 0, n, None>::value +
print<test == 3, n, Fizz>::value +
print<test == 5, n, Buzz>::value +
print<test == 15, n, FizzBuzz>::value;
};
template <int n>
struct fizzbuzz<0, n> { static constexpr auto value = 0; };
static const auto result = fizzbuzz<1000>::value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment