Skip to content

Instantly share code, notes, and snippets.

@wkubota
Last active August 29, 2015 14:09
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 wkubota/abce5609fb14b89593a3 to your computer and use it in GitHub Desktop.
Save wkubota/abce5609fb14b89593a3 to your computer and use it in GitHub Desktop.
C++のテンプレートメタプログラミングでFIZZBUZZを書いてみた。
#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