C++ Template Metaprogramming Game

Snake
Image by OpenClipart-Vectors from Pixabay

Templates in C++ are a useful feature. Without them you’d not have template functions, or more usefully template classes like vector etc.  But there is an even more useful feature called template metaprogramming. It’s a very advanced and clever feature; one I have never done and I don’t think anyone could say they’ve mastered C++ unless they are good at it.

Here’s an example of the simplest example I could find. It comes from here and what it does is generate factorials of numbers at compile time. So when you run it it comes back with the answer immediately.

// factorial.cpp

#include <iostream>

template <int N>                                                                 // (2)
struct Factorial{
    static int const value = N * Factorial<N-1>::value;
};

template <>                                                                      // (3)
struct Factorial<1>{
    static int const value = 1;
};

int main(){
    
    std::cout << std::endl;
    
    std::cout << "Factorial<5>::value: " << Factorial<5>::value << std::endl;    // (1)
    std::cout << "Factorial<10>::value: " << Factorial<10>::value << std::endl;
    
    std::cout << std::endl;

}

But if you think that is clever how about a game where every time you compile it, it makes a move and remembers the move between turns? A developer called Matt Bierner has developed a snake game using template metaprogramming.

So I downloaded it into my Ubuntu, installed Clang and clang tool just for good measure and compiled. This is the output. Iv’e snipped a lot out after the first two. Ot’s very clever, in this case, not much use but I doubt if there is any other programming language in which you could do this. The compile plays the game, running it just outputs the results. Yes it’s not exactly practical but still…

david@davidvm:~/STT-C-Compile-Time-Snake-master/stt-snake$ clang++ -std=c++1y main.cpp -o snake ; ./snake
------------------
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺▶*╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
------------------
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺*╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺▶▶╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
....
-- You Are Dead --
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
*╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺▼╺╺╺╺╺╺╺╺
╺█▲╺╺╺╺╺╺╺
╺▼▶╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺

Leave a Reply

Your email address will not be published. Required fields are marked *