This program is taken from the above paper which takes unreasonably long to compile. I belive, a simple dynamic programming solution will reduce the exponential time required by this program to compile to polynomial time. I also believe, it might be quite difficult to apply dynamic programming solution, in general, to all C++ programs of this nature. You need to have a good understanding of template meta-programming to make sense of this program. One good article by the same author is here:

This post is motivated by a anonymous comment I received on an earlier post. I am quoting him here:

"It is ___provably___ impossible to write a correct C++ parser which will complete compilation with either success or failure because the C++ template system is Turing complete. This means that code generation is based on a turing complete program. Code generation in C++ isn't based on a program description, but an actual turing complete program. As such, it is subject to the halting problem. Therefore, it is unknowable whether a compilation will complete, and unknowable if you are looking at a valid C++ program."

The only reason it takes so long to compile is because it adds in unused template arguments A and B. Once those are deleted, you give addition of the same thing 5 times, so you just replace that with multiplication.

There is also a compile-time error caused by integer overflow in a constant expression. The type of x and z need to be able to hold a 38-bit integer. Something like std::int64_t should be good enough.

Once you make the changes to get rid of useless code and allow it to compile, it finishes in about .2 seconds on my machine.