Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C++ Templates just Macros in disguise?

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?
like image 241
Roddy Avatar asked Oct 07 '08 20:10

Roddy


People also ask

Are templates just macros?

A lot of Excel users are confused about when to use macros and when to create templates. 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 more efficient than macros?

The results show that for this example, compiling templates is faster than the equivalent macro version! On top of that, templates are more maintainable, since the code is not duplicated, and the compiler can give better error messages. If you consider how templates work, then this makes a great deal of sense.

How are templates different from macros in C++?

Templates are expanded at compiler time. This is like macros. The difference is, that the compiler does type checking before template expansion. The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of the same function/class.

What do you mean by macro templates in C?

A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro.


1 Answers

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.

like image 129
Ferruccio Avatar answered Sep 20 '22 01:09

Ferruccio