From 2df38af45722b076555b9d093cbdca16c6f4bd4a Mon Sep 17 00:00:00 2001 From: Mitch Richling <11151403+richmit@users.noreply.github.com> Date: Thu, 5 Sep 2024 12:48:59 -0500 Subject: [PATCH] fmtInt is a template now --- lib/mjrmath.hpp | 44 ++++++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/lib/mjrmath.hpp b/lib/mjrmath.hpp index 80f03da..7e2633d 100644 --- a/lib/mjrmath.hpp +++ b/lib/mjrmath.hpp @@ -259,24 +259,32 @@ namespace mjr { @param fill Fill character @param base An integer (valid values: 16, 10, 8) @param rightJustify If true, then right justify. Otherwise, left. - @return A formatted string. */ - std::string fmtInt(int inInt, int width = 0, char fill = ' ', int base = 10, bool rightJustify = true) { - std::ostringstream stringStream; - if (width > 0) - stringStream << std::setfill(fill) << std::setw(width); - else - stringStream << std::setfill(fill) << std::setw(0); - if(rightJustify) - stringStream << std::right; - else - stringStream << std::left; - if (base == 16) - stringStream << std::hex << std::noshowbase; - if (base == 8) - stringStream << std::oct << std::noshowbase; - // TODO: Should throw if base is not 8, 10, or 16... - stringStream << inInt; - return stringStream.str(); + If the type of inInt is convertable to an int, then it will be converted to int and will be formated via an std::ostringstream. If it can't be converted, + then it will be passed unchanged. + @return A formatted string. */ + template + requires (std::integral) + std::string fmtInt(intType inInt, int width = 0, char fill = ' ', int base = 10, bool rightJustify = true) { + if constexpr ( !(std::same_as) && std::convertible_to) { + return fmtInt(static_cast(inInt), width, fill, base, rightJustify); + } else { + std::ostringstream stringStream; + if (width > 0) + stringStream << std::setfill(fill) << std::setw(width); + else + stringStream << std::setfill(fill) << std::setw(0); + if(rightJustify) + stringStream << std::right; + else + stringStream << std::left; + if (base == 16) + stringStream << std::hex << std::noshowbase; + if (base == 8) + stringStream << std::oct << std::noshowbase; + // TODO: Should throw if base is not 8, 10, or 16... + stringStream << inInt; + return stringStream.str(); + } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////