Comment

Comment by pjmlp

Compiler Explorer is your friend, https://godbolt.org/z/94hzK8svE

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.
parent pjmlp 4 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton