4 ms·
Here is a complete example how to generate a compile time FizzBuzz array in C++. This includes converting the numbers to string. This example does through 50.
by jbandela1 4y ago
Here is a complete example how to generate a compile time FizzBuzz array in C++. This includes converting the numbers to string. This example does through 50.
https://gcc.godbolt.org/z/1nTcdvWM5 https://gcc.godbolt.org/z/1nTcdvWM5
#include <limits>
#include <array>
#include <algorithm>
#include <utility>
#include <string_view>
template<unsigned int Num>
constexpr auto to_array(){
constexpr auto digits =
std::numeric_limits<unsigned int>::digits10;
std::array<char,digits> ar{};
auto x = Num;
int pos = 0;
while(x > 0){
ar[pos] = '0' + x % 10;
x /= 10;
++pos;
}
std::reverse(ar.begin(),ar.begin() + pos);
return std::make_pair(pos,ar);
}
template<unsigned int Num>
struct to_string{
constexpr static auto p = to_array<Num>();
constexpr static std::string_view get(){
return std::string_view(p.second.data(),p.first);
}
};
template<unsigned int Num>
constexpr std::string_view get_fizz_buzz(){
if constexpr (Num % 15 == 0) {
return "FizzBuzz";
} else if constexpr (Num % 3 == 0) {
return "Fizz";
} else if constexpr (Num % 5 == 0) {
return "Buzz";
} else{
return to_string<Num>::get();
}
}
template<std::size_t... I>
constexpr auto get_fizz_buzz_array_impl(std::index_sequence<I...>){
return std::array{get_fizz_buzz<I+1>()...};
}
template<unsigned int Val>
constexpr auto get_fizz_buzz_array(){
return get_fizz_buzz_array_impl(std::make_index_sequence<Val>());
}
#include <iostream>
int main(){
static constexpr auto ar = get_fizz_buzz_array<50>();
for(auto s:ar){
std::cout << s << "\n";
}
}
- pjmlp 4y agoMuch better than my poor attempt, thanks for sharing.