difference between a C++ macro MAX and the C++ template

A

Aakash Jain

Can someone explain me the difference between the following C++ macro
and the function MAX:

#define MAX(a, b) (((a) > (b)) ? (a) : (b))

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

Some of the differences I beleive are that the macro is expanded
inline by the preprocessor, unlike the fucntion MAX? Any other
differences? Can the two basically be used interchangably, or would
one be used over the other for certain applications?

Thanks in advance.

Aakash
 
C

Christopher Benson-Manica

Aakash Jain said:
Some of the differences I beleive are that the macro is expanded
inline by the preprocessor, unlike the fucntion MAX? Any other
differences? Can the two basically be used interchangably, or would
one be used over the other for certain applications?

Thought exercise:

int i=0, j=2;
MAX(i++,j++);

What's the difference?
 
D

David Harmon

On 13 Apr 2004 10:50:58 -0700 in comp.lang.c++, (e-mail address removed)
(Aakash Jain) wrote,
Can someone explain me the difference between the following C++ macro
and the function MAX:

#define MAX(a, b) (((a) > (b)) ? (a) : (b))

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

1. Pass MAX as a function argument to another function, e.g.
// make all numbers non-negative
std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(MAX<double>, 0.0));

2. Define a class with a private member function that happens
to be named MAX.

3. Try to solve the problems with (1) and (2) by making MAX
a member of a namespace.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top