C++ – Are C++ templates just a kind of glorified macros

ccompilermacrostemplates

From different comparisons among C++ templates and C#/Java generics like this one-

https://stackoverflow.com/questions/31693/what-are-the-differences-between-generics-in-c-and-java-and-templates-in-c/31929#31929

I got a perception that, C++ templates are implemented by some kind of preprocessing(plain text replacement prior to parsing), not compiling. Because the type checking in C++ templates resembles C macros. I mean, if there are some errors, they are errors from the generated code after processing templated code blocks, not from the templates themselves. In other words, they are just a kind of upper version of macros in C.

Then I found some other facts supporting this-

  • I thought, if C++ templates are implemented by preprocessing, there will be issues with dynamic linking(using .dll). And a quick googling supported this.

  • Another point is, integer constants can be passed as arguments to the templates. And it even supports some kind of recursion. But this recursion is not found in the compiled assembly/machine code. The recursion thing is managed in compile time by generating a functions for every recursive call and thus having a larger but faster executable binary.

Though unlike C macros, it has some superior abilities. But isn't C++ template implemented with some kind of preprocessing? How is this implemented in different C++ compilers?

Best Answer

C++ templates are a sort of dumbed down Lisp (or even more, Scheme) macros. It is a Turing-complete language which evaluates in compilation time, but it is severely limited as there is no access from that language to the underlying C++ environment. So, yes, C++ templates can be seen as some form of preprocessing, with a very limited interaction with the code being generated.

Related Topic