Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DIfference between macros and templates - compilation/build time

Tags:

c++

Macros are expanded by preprocessors and templates are by compilers.

But, in terms of compilation/build time, which one takes longer?

like image 301
user382499 Avatar asked Jul 05 '10 03:07

user382499


People also ask

What is the difference between templates and macros?

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.

Are templates compile time?

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.

Are macros compile time?

Macros are a powerful compile-time tool to make code conditionally compile across a variety of environments and targets.

Are templates resolved at compile time?

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!


1 Answers

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.

like image 86
Billy ONeal Avatar answered Sep 20 '22 23:09

Billy ONeal