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 <bstoeger@mail.tuwien.ac.at>
This commit is contained in:
Berthold Stoeger 2024-12-14 17:06:00 +01:00 committed by Michael Keller
parent 022b927755
commit 851e8bc5ee

View file

@ -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<T &>(*this);
}
template <typename base_type>
T &operator*=(base_type v) {
get_base() *= v;
return static_cast<T &>(*this);
}
template <typename base_type>
T operator*(base_type v) const {
return from_base(get_base() * v);
}
// Attn: C++ integer semantics: this always rounds towards 0!
template <typename base_type>
T &operator/=(base_type v) {
get_base() /= v;
return static_cast<T &>(*this);
}
// Attn: C++ integer semantics: this always rounds towards 0!
template <typename base_type>
T operator/(base_type v) const {
return from_base(get_base() / v);
}
};
template <typename T,