Last active
August 29, 2015 14:09
-
-
Save wkubota/abce5609fb14b89593a3 to your computer and use it in GitHub Desktop.
C++のテンプレートメタプログラミングで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 <iostream> | |
#include <string> | |
#define FIZZ "Fizz" | |
#define BUZZ "Buzz" | |
#define CRLF "\r\n"; | |
template<int N> | |
struct num { | |
static std::string value() { | |
return (N%3==0 || N%5==0) ? "":std::to_string(N).c_str(); | |
} | |
}; | |
template<int N> | |
struct buzz { | |
static std::string value() {return "";} | |
}; | |
template<> | |
struct buzz<0> { | |
static std::string value() {return BUZZ;} | |
}; | |
template<int N> | |
struct fizz { | |
static std::string value() {return "";} | |
}; | |
template <> | |
struct fizz<0> { | |
static std::string value() {return FIZZ;} | |
}; | |
template <int N> | |
struct check{ | |
static std::string value() { | |
return fizz<N%3>::value() + buzz<N%5>::value() + num<N>::value(); | |
} | |
}; | |
template <int N, int M> | |
struct loop { | |
static std::string value() { | |
std::string crlf = CRLF; | |
std::string val = check<N>::value() + crlf + loop<N+1, M-1>::value(); | |
return val; | |
} | |
}; | |
template <int N> | |
struct loop<N, 0> { | |
static std::string value() { | |
return CRLF; | |
} | |
}; | |
int main() | |
{ | |
std::cout << loop<1, 100>::value() << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment