## Saturday, June 12, 2010

### Template Vs Macro

• Macros just expanded out by the compiler, which means code is copied around.
• Macros are not type safe. A template will compare the input types and check them against the type you spec'ed when using it.
• Macros don't obey C++'s namespaces and locality rules they can be active in unexpected places in the code. Consider what happen if someone was to make a macro "i" in a random header some where.
• The result of the macro is what the compiler really works on so errors are more troublesome to find.. it helps to know that with gcc and g++ the "-E" command line option will stop after the pre-processor has completed.

For example;
//compile with g++ file_name
#define MIN(a,b) (((a)<(b)) ? (a) : (b))

template<class T> T min(T a,T b) { return (a<b) ? a : b; }

int main()
{
int x = 10;
int y = 20;

int macro  = MIN(x*3,y);
int tplate = min<int>(x*3,y);
}


Now expand it and view the result , notice the macro duplicated its inputs;
//run g++ -E file_name
# 1 "macro_template.cpp"
# 1 ""
# 1 ""
# 1 "macro_template.cpp"

template<class T> T min(T a,T b) { return (a<b) ? a : b; }

int main()
{
int x = 10;
int y = 20;

int macro = (((x*3)<(y)) ? (x*3) : (y));
int tplate = min<int>(x*3,y);
}