core: make interpolate() a template

Make the type the interpolate() function works on a template type,
so that this can be used for arbitrary unit types without warnings.
Internally, it does its math using floating point arithmetics anyway,
so no risk of overflow. (Exception: when just taking the middle point,
but I would hope that no part of the code lives on the edge such that
addition of two values gives an overflow.)

Moreover, add an "math.h" include so that the header becomes
independent of others.

Signed-off-by: Berthold Stoeger <bstoeger@mail.tuwien.ac.at>
This commit is contained in:
Berthold Stoeger 2024-12-14 08:17:20 +01:00
parent 9f250458f6
commit 133bc50d53

View file

@ -2,8 +2,16 @@
#ifndef INTERPOLATE_H #ifndef INTERPOLATE_H
#define INTERPOLATE_H #define INTERPOLATE_H
/* Linear interpolation between 'a' and 'b', when we are 'part'way into the 'whole' distance from a to b */ #include <type_traits>
static inline int interpolate(int a, int b, int part, int whole) #include <math.h> // lrint()
/* Linear interpolation between 'a' and 'b', when we are 'part'way into the 'whole' distance from a to b
* Since we're currently stuck with C++17, we have this horrible way of testing whether the template
* parameter is an integral type.
*/
template <typename T,
std::enable_if_t<std::is_integral<T>::value, bool> = true>
T interpolate(T a, T b, int part, int whole)
{ {
/* It is doubtful that we actually need floating point for this, but whatever */ /* It is doubtful that we actually need floating point for this, but whatever */
if (whole) { if (whole) {