From 20bb11cd039d300c2b3056ed3cabe87ec3e68e42 Mon Sep 17 00:00:00 2001 From: Berthold Stoeger Date: Sat, 14 Dec 2024 17:06:00 +0100 Subject: [PATCH] core: implement scalar multiplication/division for unit types Allow multiplication/division of unit types with scalars, such as depth * 4 or depth / 4 Multiplication the other way round (4 * depth) is not currently supported, because that needs some template trickery. Might do this later or wait for our switch to C++20, where we could use concepts to make that trickery more palatable. Signed-off-by: Berthold Stoeger --- core/units.h | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/core/units.h b/core/units.h index 9636573aa..53dd1caa8 100644 --- a/core/units.h +++ b/core/units.h @@ -89,6 +89,14 @@ * For now, addition and subtraction of values of the same type * are supported. * + * Moreover, multiplication and division with an integral are + * suppoerted. Attention: the latter uses standard C++ integer + * semantics: it always rounds towards 0! + * + * Note: multiplication with a scalar is currently only supported + * from the right: "depth * 2" is OK, "2 * depth" is (not yet) OK, + * because that needs a free standing "operator*()" operator. + * * A free standing interpolate() function can be used to interpolate * between types of the same kind (see also the interpolate.h header). * @@ -144,6 +152,26 @@ struct unit_base { get_base() -= v2.get_base(); return static_cast(*this); } + template + T &operator*=(base_type v) { + get_base() *= v; + return static_cast(*this); + } + template + T operator*(base_type v) const { + return from_base(get_base() * v); + } + // Attn: C++ integer semantics: this always rounds towards 0! + template + T &operator/=(base_type v) { + get_base() /= v; + return static_cast(*this); + } + // Attn: C++ integer semantics: this always rounds towards 0! + template + T operator/(base_type v) const { + return from_base(get_base() / v); + } }; template