Compile time Towers of Hanoi 2005-03-08


Blame this guy for inspiring me (but read his article - it's a great summary of the basics of template metaprogramming):


    #include <iostream>
    
    template<int From, int To, int Using, int N>
        struct Hanoi {
            typedef Hanoi<From,Using,To,N-1> prev_move;
            typedef Hanoi<Using,To,From,N-1> next_move;
    
            enum {
                move_from = From,
                  move_to = To
            };
    
            static void exec() {
                prev_move::exec();
                std::cout << "Move from " << move_from << " to " << move_to << std::endl;
                next_move::exec();
            }
        };
    
    template<int From, int To, int Using>
        struct Hanoi<From,To,Using,0> {
            static void exec()
            {
            }
        };
    
    int main()
    {
        Hanoi<1,3,2,8>::exec();
    }

Note that while the template allows you to manipulate the solution at compile time, the exec() function generates the textual output at runtime, and the program is going to grow ridiculously big for large number of discs considering the simplicity of the algorithm.

(Since I'm lazy, the overall approach mimics this C implementation)


blog comments powered by Disqus