Benefits and drawbacks of metaprogramming
After our discussion about template metaprogramming, the following are the advantages we derive:
- Template metaprogramming has no side effect since it is immutable, so we cannot modify an existing type
- There is better code readability compared to code that does not implement metaprogramming
- It reduces repetition of the code
Although we can gain benefits from template metaprogramming, there are several disadvantages, which are as follows:
- The syntax is quite complex.
- The compilation time takes longer since we now execute code during compile-time.
- The compiler can optimize the generated code much better and perform inlining, for instance, the C
qsort()
function and the C++sort
template. In C, theqsort()
function takes a pointer to a comparison function, so there will be one copy of theqsort
code that is not inlined. It will make a call through the pointer to the comparison routine. In C++,std::sort
is a template, and it can take afunctor
object as a comparator...