Created
May 15, 2015 22:03
-
-
Save 1995eaton/48dfbadd257261665ae4 to your computer and use it in GitHub Desktop.
FizzBuzz with C++ template metaprogramming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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