Skip to content

Instantly share code, notes, and snippets.

@k06a
Forked from bgaff/fizzbuzz.cpp
Last active May 25, 2016 05:57
Show Gist options
  • Save k06a/f3cbc6533dec54bb301a880c8f231aa4 to your computer and use it in GitHub Desktop.
Save k06a/f3cbc6533dec54bb301a880c8f231aa4 to your computer and use it in GitHub Desktop.
FizzBuzz C++: Template Recursion
/*
* fizzbuzz.cpp
*
* Created on: Apr 25, 2012
* Author: Brian Geffon
*
* Modified on: May 25, 2016
* Author: Anton Bukov
*
* fizzbuzz solved without looping or conditionals using only template recursion.
*/
#include <iostream>
template <bool P> struct FizzBuzzPrinter {
template<typename T>
static void print(T value) {
std::cout << value;
}
};
template <> struct FizzBuzzPrinter<false> {
template<typename T>
static void print(T value) {}
};
template <int N> struct FizzBuzz: FizzBuzz<N-1> {
FizzBuzz() {
FizzBuzzPrinter<(N % 3) && (N % 5)>::print(N);
FizzBuzzPrinter<!(N % 3)>::print("Fizz");
FizzBuzzPrinter<!(N % 5)>::print("Buzz");
std::cout << std::endl;
}
};
template <> struct FizzBuzz<0> {};
int main (int argc, char **argv)
{
FizzBuzz<100> p;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment