The difference between macros and templates - compilation / assembly time

Macros are extended by preprocessors and macros are expanded by compilers.

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

+5
source share
4 answers

Templates undoubtedly take longer.

However, templates are much more powerful and obey C ++ syntax rules, while macros do not work.

The reason that templates take longer is because you may have a recursive template, and all these recurring events must be generated. This is the basis on which loop constructs are built in the Metaprogramming template. Macros, by contrast, cannot call themselves and therefore are limited to one extension.

, , 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
}

, , (Factorial<4>) 5 . .

+12

, . , /. , .

, . , , .

+1

, . , #define min(i, j) (((i) < (j)) ? (i) : (j))
int x = min (a++,b)
int x = (((a++) < (b)) ? (a++) : (b))
'a' .
template<class T> T min (T i, T j) { return ((i < j) ? i : j) }
, , , . , , , .

+1

All Articles