Created
July 5, 2022 10:05
-
-
Save RoyBellingan/746b2c09eeb9897dfc77974efd0ba459 to your computer and use it in GitHub Desktop.
Custom Formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <fmt/color.h> | |
#include <fmt/format.h> | |
#include <iostream> | |
struct X { | |
int id; | |
uint8_t r{1}; | |
uint8_t g{2}; | |
uint8_t b{3}; | |
}; | |
template <> | |
struct fmt::formatter<X> : fmt::formatter<string_view> { | |
bool m1 = false; | |
bool m2 = false; | |
int w = 0; | |
constexpr auto parse(fmt::format_parse_context& ctx) { | |
std::string clean; | |
auto pos = ctx.begin(); | |
while (pos != ctx.end() && *pos != '}') { | |
auto& c = *pos; | |
switch (c) { | |
case 'h': | |
case 'H': | |
m1 = true; | |
break; | |
default: | |
clean.append(pos); | |
} | |
++pos; | |
} | |
fmt::format_parse_context copy(clean); | |
fmt::formatter<string_view>::parse(copy); | |
return pos; // expect `}` at this position, otherwise, | |
// it's error! exception! | |
} | |
// constexpr auto parse(fmt::format_parse_context& ctx) { | |
// return ctx.begin(); | |
// } | |
auto format(const X& obj, fmt::format_context& ctx) { | |
if (m1) { | |
std::string temp; | |
fmt::format_to(std::back_inserter(temp), "({}, {}, {})", | |
obj.r, obj.g, obj.b); | |
return fmt::formatter<string_view>::format(temp, ctx); | |
} else { | |
return fmt::format_to(ctx.out(), "{}", obj.id); | |
} | |
} | |
}; | |
int main() { | |
X x; | |
x.id = 3435; | |
fmt::print("{0} - {0:h^20} \n", x); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment