by pjmlp · 4y ago · 0 comments
constexpr std::string get_fizzbuzz(int number) {
if (number % 15 == 0) {
return "FizzBuzz";
} else if (number % 3 == 0) {
return "Fizz";
} else if (number % 5 == 0) {
return "Buzz";
}
return std::to_string(number); // convert to string
}The article is also wrong because std::to_chars isn't constexpr so you can't use that.
In one thing you're actually right, I should have used a string_view for the return value instead.
#include <vector>
#include <string>
#include <algorithm>
#include <string>
#include <cstdio>
constexpr std::string_view get_fizzbuzz(int number) {
if (number % 15 == 0) {
return "FizzBuzz";
} else if (number % 3 == 0) {
return "Fizz";
} else if (number % 5 == 0) {
return "Buzz";
}
return std::to_string(number); // convert to string
}
int main() {
static constexpr auto value = get_fizzbuzz(15);
puts(value.data());
}
The template metaprogramming to expand all values for get_fizzbuzz() is left as exercise.Call get_fizzbuzz(11) and you'll see the error.
Although I still think with a mix of template metaprogramming and constexpr might be possible, however it would be a very low ROI on such example.
And it would still be worse than the other languages, so defeat accepted.
There's some joke here about authors using "left as exercise to the reader" to skip debugging their broken code.