C template meta programming




















Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Kalob Taulien - Dec 20 ' Arghya Sarkar - Dec 11 ' Michael R. Pascal Thormeier - Dec 30 ' DEV Community is a community of , amazing developers We're a place where coders share, stay up-to-date and grow their careers. Create account Log in. Twitter Facebook Github Instagram Twitch. Upload image. Submit Preview Dismiss. Hide child comments as well Confirm.

Log in Create account. In addition we perform a thousand test operations on the variable i. Another way would be to write the code the following way:. This is the way a Template Metaprogram would expand a loop. Now we perform exactly a thousand additions, but this method also has a prize. The code size increase, meaning that we theoretically could take a performance hit by increasing the number of page faults. In practice, though, code is often invoked multiple times and already loaded in cache.

Again, the thing to notice is that there is no loop in the resulting binary code. The loop unrolls itself to produce code like:. Note that if func was not defined inside ELSE this would be a simple compile-time assert breaking compilation on 4!

Included as a sample is a small class that does generic CRC C yclic R edundancy C odes - a set of simple hash algorithms calculations. The class uses a set of parameters that are define :d at the top of the header. The main reason I chose CRC for this article is that the CRC algorithms usually use a lookup table based on a set of parameters, making the example somewhat similar to my original problem. The class generate a lookup table with entries at compile time. The implementation is pretty straightforward, and I hope that the comments in the source is enough to explain usage of the class.

In some cases I have used macros where TMP would have been a possible solution. So we have defined a recursion that calculates the factorial of an integer. What is weird is that this calculation happens entirely at compile time. When we run this code, the first six values of the factorial series have already been calculated, and we will just be reading the last value from the code the compiler has created.

So we have seen how to do recursions via template meta programming. Next we will see how to write conditional statements that are evaluated at compile time.



0コメント

  • 1000 / 1000