Are C++ Templates just Macros in disguise?

Roddy picture Roddy · Oct 7, 2008 · Viewed 22.4k times · Source

I've been programming in C++ for a few years, and I've used STL quite a bit and have created my own template classes a few times to see how it's done.

Now I'm trying to integrate templates deeper into my OO design, and a nagging thought keeps coming back to me: They're just a macros, really... You could implement (rather UGLY) auto_ptrs using #defines, if you really wanted to.

This way of thinking about templates helps me understand how my code will actually work, but I feel that I must be missing the point somehow. Macros are meant evil incarnate, yet "template metaprogramming" is all the rage.

So, what ARE the real distinctions? and how can templates avoid the dangers that #define leads you into, like

  • Inscrutable compiler errors in places where you don't expect them?
  • Code bloat?
  • Difficulty in tracing code?
  • Setting Debugger Breakpoints?

Answer

Ferruccio picture Ferruccio · Oct 7, 2008

Macros are a text substitution mechanism.

Templates are a functional turing-complete language that is executed at compile time and is integrated into the C++ type system. You can think of them as a plugin mechanism for the language.