diff options
Diffstat (limited to 'src/base.h')
-rw-r--r-- | src/base.h | 28 |
1 files changed, 28 insertions, 0 deletions
@@ -10,6 +10,7 @@ #include <memory> #include <string_view> #include <chrono> +#include <optional> namespace cru { @@ -63,4 +64,31 @@ namespace cru if (!condition) throw std::invalid_argument(error_message.data()); } + + template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> + float Coerce(const T n, const std::optional<T> min, const std::optional<T> max) + { + if (min.has_value() && n < min.value()) + return min.value(); + if (max.has_value() && n > max.value()) + return max.value(); + return n; + } + + template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> + float Coerce(const T n, const std::nullopt_t, const std::optional<T> max) + { + if (max.has_value() && n > max.value()) + return max.value(); + return n; + } + + template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> + float Coerce(const T n, const std::optional<T> min, const std::nullopt_t) + { + if (min.has_value() && n < min.value()) + return min.value(); + return n; + } + } |