We talked about the “fizz buzz” programming test today, I thought about implementing this with in C++ but with meta-programming. Ideally it would generate the output already during compilation time.
My current code uses templates, but it still has to be executed in order to produce the output. See it on Ideone.
I still use std::cout <<
in order to print the output on the screen. The FizzBuzz<i>::value
will give either i
, -1
(Fizz), -2
(Buzz), or -3
(FizzBuzz). Then word<value>
is defined for the negative numbers and gives a char const *
:
template <int i>
struct Print {
static void print() {
Print<i - 1>::print();
auto const value = FizzBuzz<i>::value;
if (value < 0) {
std::cout << word<value>() << std::endl;
} else {
std::cout << value << std::endl;
}
}
};
The loop is gone due to recursion, there is a Print<0>
which stops it.
Is there some way to print out word<value>()
or value
, which are known at compile time during compilation? This will probably not work with every compiler, so I am happy with a solution that works with GCC and/or Clang.