Created
September 2, 2020 17:32
-
-
Save dekrain/016d5b38f811c74b107724efb346dd0d to your computer and use it in GitHub Desktop.
Fizzbuzz, but _advanced_
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 <tuple> | |
template <size_t N> | |
struct FizzBase { | |
char const* msg; | |
bool fizz(int x) const { | |
if (x % N == 0) | |
return (std::cout << msg), true; | |
return false; | |
} | |
}; | |
template <typename... Ts> | |
struct FizzGame { | |
std::tuple<Ts...> bases; | |
FizzGame(Ts... b) : bases(static_cast<Ts&&>(b)...) {} | |
int x = 0; | |
void operator*() { | |
bool acc = false; | |
[&]<size_t... I>(std::index_sequence<I...>) { | |
((acc |= get<I>(bases).fizz(x)), ...); | |
} (std::index_sequence_for<Ts...>()); | |
if (!acc) | |
std::cout << x; | |
std::cout << '\n'; | |
} | |
FizzGame& operator++() { | |
++x; | |
return *this; | |
} | |
FizzGame& begin() {return *this; } | |
}; | |
template <typename... Ts> | |
FizzGame(Ts...) -> FizzGame<Ts...>; | |
int main() { | |
constexpr size_t game_size = 100ull; | |
auto gam = FizzGame(FizzBase<3>{"fizz"}, FizzBase<5>{"buzz"}); | |
for (size_t i = 0; i < game_size; ++i) | |
*++gam; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment