Macros are expanded by preprocessors and templates are by compilers.
But, in terms of compilation/build time, which one takes longer?
A macro is a recording of formatting changes and other steps that can be replayed quickly. A template is a pre-formatted spreadsheet with headers and formulas – awaiting your data.
The use of templates can be thought of as compile-time polymorphism. The technique is used by a number of languages, the best-known being C++, but also Curl, D, Nim, and XL.
Macros are a powerful compile-time tool to make code conditionally compile across a variety of environments and targets.
All the template parameters are fixed+known at compile-time. If there are compiler errors due to template instantiation, they must be caught at compile-time!
Templates undoubtedly take longer.
However, templates are significantly more powerful and obey C++ syntactical rules, whereas macros do not.
The reason Templates take longer is because you can have a template which is recursive, and all of those recurrences need to be generated. This is the foundation upon which looping constructs in Template Metaprogramming are built. Macros, in contrast, cannot call themselves, and are therefore limited to a single expansion.
For example, take the following code, shamelessly stolen from Wikipedia:
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
Note how the factorial is calculated at compile time, and for the first call (Factorial<4>
), the compiler needs to expand the template 5 times. Macros cannot do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With