Created
October 1, 2013 13:54
-
-
Save pasberth/6778805 to your computer and use it in GitHub Desktop.
template で fizzbuzz
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
#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