Template or Macro

Started by
9 comments, last by King Mir 8 years, 12 months ago

Hi,

Is it better to have a template or macro and why ?

Example of one macro which could be a template :


#define SAFE_DELETE( p ) { delete p; p = NULL; }

Thanks

Advertisement
Is it better to have a sandwich or a screwdriver, and why?

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

"sandwich" is needed to survive, "screwdriver" was not there in paleolithic era and all was fine.

You can look at this link to learn what is paleothic era : http://en.wikipedia.org/wiki/Paleolithic

That's a pretty impressive way to miss the point entirely, I have to admit.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

This thread makes me want a third option: An alcoholic beverage.

All Snark aside -- in general you should prefer a template if a template can reasonably do the thing you need; however, you need to temper that with other constraints -- there are things that macros can do that templates can't (and vice versa), or sometimes a macro just might fit into an existing codebase more cleanly (assuming you've audited that codebase and are sure your macro isn't going to cause any conflicts in the first place).

Macros are dumb; don't do dumb things unnecessarily. But once in a rare while, something dumb is the smart choice.

throw table_exception("(? ???)? ? ???");

There are a few templates in the standard library for safe delete already: here, here and here, for example. So the standard apparently thought it was better to use templates in this case at least.

I think you should prefer templates unless you have a good reason not to.

If you pass an array to SAFE_DELETE it will still compile, but using templates you can force this to give you an error.

int arr[5];
SAFE_DELETE(arr);

My rule of thumb is to restrict the use of macros constructs that are not related to ordinary c++ code. First example is conditional compilation, i.e. to include or exclude some portions of code that target specific platforms. Another example is assertions, which can't be considered normal code that is supposed to be part of the execution. A third example could be error logging (but that could depend on the context). I'm also using some macros to define and embed shader code inside c++ code.

So in your example, pointer deletion *is* normal code and should *not* use macros. Read up on std::unique_ptr and std::shared_ptr and you'll see that those templates work way better anyway.

openwar - the real-time tactical war-game platform

Template when you can, macro when you must.

This topic is closed to new replies.

Advertisement