tags:

views:

66

answers:

3

Macros are expanded by preprocessors and templates are by compilers.

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

+5  A: 

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.

Billy ONeal
It's also interesting to point out that, while not supported by C++0x or the current standard, template "concepts" can still be worked in. Boost has a Concept library which allows you to validate the use of templates and produce much more meaningful errors, whereas macros are notorious for being difficult to figure out the cause of a compilation error when misused.
Shirik
A: 

Did you check the msdn link on this

http://msdn.microsoft.com/en-us/library/z3f89ch8(VS.80).aspx#_core_When_Should_You_Use_Templates.3fAnchor1

Templates take longer build time but its advantages outweigh this extra time taken for compiling. THe msdn link gives you enough information.

ckv
+1  A: 

Templates cause code substitution, but obey a certain set of rules. That means that the compiler checks types before creating the new class/object. Macro are parsed by the Pre-processor, which only replaces text.

So, templates will always take longer to process. The code generated by the Macro, however, can take a certain time to process.

Bruno Brant