Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created October 1, 2013 13:54
Show Gist options
  • Save pasberth/6778805 to your computer and use it in GitHub Desktop.
Save pasberth/6778805 to your computer and use it in GitHub Desktop.
template で fizzbuzz
#include <string>
#include <iostream>
template <bool cond>
struct print_if
{
static void run(std::string msg) {}
};
template <>
struct print_if<true>
{
static void run(std::string msg)
{
std::cout << msg << std::endl;
}
};
template <>
struct print_if<false>
{
static void run(std::string msg) {}
};
template <unsigned long N>
struct fizzbuzz
{
static void run()
{
fizzbuzz<N-1>::run();
print_if<N % 3 == 0 && N % 5 != 0>::run("Fizz");
print_if<N % 3 != 0 && N % 5 == 0>::run("Buzz");
print_if<N % 3 == 0 && N % 5 == 0>::run("FizzBuzz");
print_if<N % 3 != 0 && N % 5 != 0>::run(std::to_string(N));
}
};
template <>
struct fizzbuzz<0>
{
static void run() {}
};
int main()
{
fizzbuzz<15>::run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment