The rule of thumb in C++ is to avoid macros whenever possible.
For example, your macro will suffer from repeated evaluation of arguments if I pass something like BOUNDED(x++, low++, hi++)
.
If you want to retain the generic nature of the macro, then why not write
template<typename Y>
inline Y Bounded(Y x, Y lo, Y hi)
{
return x < lo ? lo : x > hi ? hi : x;
}
I can't see this being slower than the macro approach. Note that the compiler may ignore inline
as it sees fit. Profile the performance to be sure. You could consider passing const Y& x
etc. for large types, but this will probably wind up slower for the Y
= double
case.