Files CCore/inc/gadget/UtilFunc.h CCore/src/gadget/UtilFunc.cpp
Here is a collection of some popular functions.
ToConst() makes a constant reference from a reference. Sometimes useful.
template <class T>
const T & ToConst(T &obj) { return obj; }
Min()/Max() — these functions are intended to be used with simple types and can be used in constant expressions. They are implemented in a straightforward way.
template <class T> constexpr T Min(T a,T b) { return (a<b)?a:b; } template <class T> constexpr T Max(T a,T b) { return (a<b)?b:a; }
Cap() adjusts the given value x to fit it into the given interval [a,b]. To work properly, make sure that a <= b. If x is too low, a is returned, if x is too large, b is returned. Otherwise, x is returned. Pay attention, that x is a middle argument!
template <class T>
constexpr T Cap(T a,T x,T b) { return (x<a)?a:( (b<x)?b:x ); }
Fit() checks that the given value x belongs to the interval [a,b]. To work properly, make sure that a <= b. Pay attention, that x is a middle argument!
template <class T>
constexpr bool Fit(T a,T x,T b) { return a<=x && x<=b; }
Sq() calculates the square of the argument.
template <class T>
constexpr T Sq(T x) { return x*x; }
Diff() performs differentiation, i.e. subtracts a value from the previous one and records the new value.
template <class T>
T Diff(T &t,T a) { T ret(a-t); t=a; return ret; }
Consider an example:
int var=x0; int d1=Diff(var,x1); // d1 <- x1-x0 , var <- x1 int d2=Diff(var,x2); // d2 <- x2-x1 , var <- x2 int d3=Diff(var,x3); // d3 <- x3-x2 , var <- x3
Change() assign a new value if it is different than the old value of the object. If this happens the return value is true, otherwise — false.
template <class T>
bool Change(T &obj,T val)
{
if( obj!=val )
{
obj=val;
return true;
}
return false;
}
Bit...() — four bit manipulation functions:
template <class UInt,class S> void BitSet(UInt &t,S bits); // set bits template <class UInt,class S> void BitClear(UInt &t,S bits); // clear bits template <class UInt,class S> UInt BitTest(UInt t,S bits); // check if at least one of bits is set template <class UInt,class S> bool BitTestAll(UInt t,S bits); // check if all bits are set
These functions make bit manipulation expressions more simple and verbose and resolve the type conversion problem. The second argument is explicitly casted to the type of the first one.