Mercurial > minori
diff include/core/strings.h @ 122:bc218c9d2ea6
strings: convert ToInt() to be a template
ini: conform to new strings.cc changes
author | Paper <mrpapersonic@gmail.com> |
---|---|
date | Wed, 08 Nov 2023 21:36:09 -0500 |
parents | 39521c47c7a3 |
children | bc8d2ccff09c |
line wrap: on
line diff
--- a/include/core/strings.h Wed Nov 08 18:13:56 2023 -0500 +++ b/include/core/strings.h Wed Nov 08 21:36:09 2023 -0500 @@ -4,6 +4,8 @@ #include <string> #include <vector> #include <array> +#include <limits> +#include <stdexcept> #include <cstdint> class QString; @@ -39,7 +41,24 @@ QString ToQString(const std::wstring& wstring); /* arithmetic :) */ -int ToInt(const std::string& str, int def = 0); +template<typename T = int> +T ToInt(const std::string& str, T def = 0) { + auto clamp = [](const T& val, const T& min, const T& max){ + return std::max(min, std::min(val, max)); + }; + + try { + if constexpr (std::is_signed<T>::value) { + return clamp(std::stoll(str), std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); + } else if constexpr (std::is_unsigned<T>::value) { + return clamp(std::stoull(str), std::numeric_limits<T>::max(), std::numeric_limits<T>::max()); + } else { + throw std::invalid_argument("it no worky"); + } + } catch (std::invalid_argument const& ex) { + return def; + } +} bool ToBool(const std::string& s, const bool def = false); std::string ToUtf8String(const bool b);