REWORKED improved implementation of jkqtp_bounded<T>(TIn v), which now can cope with cases where TIn is signed, but T is unsigned

This commit is contained in:
jkriege2 2024-01-09 17:38:54 +01:00
parent 4a7b6b60d1
commit 0ae712ad43
2 changed files with 25 additions and 4 deletions

View File

@ -184,6 +184,10 @@ Changes, compared to \ref page_whatsnew_V4_0_0 "v4.0.0" include:
<li>NEW: Added JKQTMathText::useGuiFonts()</li>
<li>NEW: Added JKQTMathText::setFontOptions(), which allows to make fonts initially e.g. bold, italic, ... and extended JKQTMathText::setFontSpecial() accordingly</li>
</ul></li>
<li>JKQTPCommon:<ul>
<li>NEW: iadded variant of jkqtp_bounded<T>(TIn v), which limits to the limits of a type T and can cope with cases where TIn is signed, but T is unsigned</li>
</li>
</ul></li>
<li>JKQTFastPloter:<ul>
<li>BREAKING: This class/library is now deprecated and will be removed in future versions!</li>
</ul></li>

View File

@ -30,6 +30,7 @@
#include <vector>
#include <QString>
#include <functional>
#include <type_traits>
#ifdef max
# undef max
@ -233,7 +234,7 @@ inline T jkqtp_boundedRoundTo(const double& v) {
return jkqtp_boundedRoundTo<T>(std::numeric_limits<T>::min(), v, std::numeric_limits<T>::max());
}
/** \brief bounds a value \a v to the given range \a min ... \a max
/** \brief limits a value \a v to the given range \a min ... \a max
* \ingroup jkqtptools_math_basic
*
* \tparam T a numeric datatype (int, double, ...)
@ -243,9 +244,25 @@ inline T jkqtp_boundedRoundTo(const double& v) {
*/
template<typename T>
inline T jkqtp_bounded(T min, T v, T max) {
if (v<min) return min;
if (v>max) return max;
return v;
return (v<min) ? min : ((v>max)? max : v);
}
/** \brief limits a value \a v to the range of the given type \a T , i.e. \c std::numeric_limits<T>::min() ... \c std::numeric_limits<T>::max()
* \ingroup jkqtptools_math_basic
*
* \tparam T a numeric datatype (int, double, ...) for the output
* \tparam TIn a numeric datatype (int, double, ...) or the input \a v
* \param v the value to round and cast
*
* \note As a special feature, this function detectes whether one of T or TIn are unsigned and then cmpares against a limit of 0 instead of \c std::numeric_limits<T>::min() .
*/
template<typename T, typename TIn>
inline T jkqtp_bounded(TIn v) {
if (std::is_integral<T>::value && std::is_integral<TIn>::value && (std::is_signed<TIn>::value!=std::is_signed<T>::value)) {
return (v<TIn(0)) ? T(0) : ((v>std::numeric_limits<T>::max())? std::numeric_limits<T>::max() : static_cast<T>(v));
} else {
return (v<std::numeric_limits<T>::min()) ? std::numeric_limits<T>::min() : ((v>std::numeric_limits<T>::max())? std::numeric_limits<T>::max() : static_cast<T>(v));
}
}
/** \brief compare two floats \a a and \a b for euqality, where any difference smaller than \a epsilon is seen as equality