Sign in to follow this  
Alundra

Template or Macro

Recommended Posts

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);

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Prefer templates over macros when both are usable, because templates offer better type safety and interact more intuatively with other language features. For example, safe delete could be written as a template in such a way that you get a compiler error when you try to delete an int, but you can't do that with a macro.

 

I veiw it as a hiarchy of tools for code reuse. It goes roughly as follows:

1) loops

2) functions

3) templates

4) macros

 

You use a loop when you need to do the same operation, for different values in sequence

You use a function when you need to do the same operation, for different values out of sequence

You use a template function when you need to do the same operation, for different values of different types.

You use a Macro when you need to do the same operation, but there are differences in structure.

 

(Polymoric classes could also fit in this hiarchy, between functions and templates)

 

There are other uses of macros too where templates obviously cannot be used.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this