Thomas Sampson

Clamping Values

Leave a comment

Using the Pre-processor

“Macros like this have so many drawbacks, just thinking about them is painful” – Scott Meyers.

#define min(a,b)                      (((a) < (b)) ? (a) : (b))
#define max(a,b)                      (((a) > (b)) ? (a) : (b))
#define clamp(value, lb, ub)          max( lb, min( ub, value ))

Using Templates (Inline)

A much safer and elegant approach, relies on T::operator< and T::operator> to perform the evaluation.

template<typename T>
inline T Min(const T& a, const T& b) { return (a < b)? a : b; }

template<typename T>
inline T Max(const T& a, const T& b) { return (a > b)? a : b; }

template<typename T>
inline T Clamp(const T& value, const T& lb, const T& ub) { return Max<T>(lb, Min<T>(ub, value)); }
Advertisements

Author: tomtech999

I have recently graduated with a 1st class degree in MComp Games Software Development at Sheffield Hallam University, focusing primarily on application development in C++, with experience in graphics programming, scripting languages, DVCS/VCS and web technology. In my spare time I enjoy Drumming, Reading and Snowboarding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s