99 bottles of beer: Difference between revisions

→‎{{header|C++}}: added template metaprogramming solution
(→‎{{header|C++}}: added template metaprogramming solution)
Line 314:
bottle_song::song song(100);
song.sing(std::cout);
}</c>
 
=== A template metaprogramming solution ===
Of course, the output of the program always looks the same. One may therefore question why the program has to do all that tedious subtracting during runtime. Couldn't the compiler just generate the code to output the text, with ready-calculated constants? Indeed, it can, and the technique is called template metaprogramming. The following short code gives the text without containing a single variable, let alone a loop:
 
<c>#include <iostream>
#include <ostream>
 
template<int max, int min> struct bottle_countdown
{
static const int middle = (min + max)/2;
static void print()
{
bottle_countdown<max, middle+1>::print();
bottle_countdown<middle, min>::print();
}
};
 
template<int value> struct bottle_countdown<value, value>
{
static void print()
{
std::cout << value << " bottles of beer on the wall\n"
<< value << " bottles of beer\n"
<< "Take one down, pass it around\n"
<< value-1 << " bottles of beer\n\n";
}
};
 
int main()
{
bottle_countdown<100, 1>::print();
}</c>
 
973

edits