Last active
May 22, 2017 13:39
-
-
Save FinalTheory/ec4b0da8447e491971f92540b4f0b8b8 to your computer and use it in GitHub Desktop.
C++ Template Hanoi
This file contains 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
#include <iostream> | |
#include <utility> | |
template <int, typename T, T a, T b, T c> | |
struct hanoi; | |
template <typename seq1, typename seq2> | |
struct concat; | |
template <typename... Args> | |
struct sequence {}; | |
template <typename T, T a, T b> | |
struct pair { | |
static constexpr auto first = a; | |
static constexpr auto second = b; | |
}; | |
template <typename... Args1, typename... Args2> | |
struct concat<sequence<Args1...>, sequence<Args2...>> { | |
using type = sequence<Args1..., Args2...>; | |
}; | |
template <typename T, T a, T b, T c> | |
struct hanoi<1, T, a, b, c> { | |
using type = sequence<pair<T, a, c>>; | |
}; | |
template <int n, typename T, T a, T b, T c> | |
struct hanoi { | |
using type = typename concat< | |
typename concat<typename hanoi<n - 1, T, a, c, b>::type, | |
sequence<pair<T, a, c>> | |
>::type, | |
typename hanoi<n - 1, T, b, a, c>::type | |
>::type; | |
}; | |
// here we got type T for sequence<> | |
template <typename T> | |
void print(T) {} | |
template <typename T, typename... Args> | |
void print(sequence<T, Args...>) { | |
std::cout << T::first << "->" << T::second << std::endl; | |
print(sequence<Args...>()); | |
} | |
int main(int, const char*[]) { | |
print(typename hanoi<7, char, 'A', 'B', 'C'>::type()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment