-
-
Save k06a/f3cbc6533dec54bb301a880c8f231aa4 to your computer and use it in GitHub Desktop.
FizzBuzz C++: Template Recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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