CKTIS / C++
std::formatter: het formatteringscontract van een type
Een specialisatie std::formatter<T, charT> bepaalt hoe de specificatie wordt ontleed en een T-waarde wordt geschreven.
Versie: C++23
Syntax
template<class T, class CharT = char>
struct std::formatter;
// A usable specialization provides conceptually:
constexpr auto parse(std::basic_format_parse_context<CharT>& ctx);
template<class FormatContext>
auto format(const T& value, FormatContext& ctx) const;std::formatter<T, charT> uit <format> is het aanpassingspunt dat std::format en verwante functies per argument gebruiken. Een formatter voldoet aan BasicFormatter/Formatter: parse(ctx) ontleedt het deel na de dubbele punt en retourneert het eerste niet-verbruikte teken, gewoonlijk }, terwijl format(value, ctx) via ctx.out() schrijft en de iterator na zijn uitvoer retourneert.
Het voorbeeld specialiseert std::formatter<Point> voor een programmagedefinieerd type. parse retourneert ctx.begin() en accepteert dus alleen een lege specificatie; format delegeert de coördinaten aan std::format_to. Het resultaat is p=(3, 4). De specialisatie moet zichtbaar zijn wanneer de letterlijke formatstring wordt gecontroleerd. Opties uit parse mogen in de formatter worden bewaard voor format.
Een onverteerd deel, behalve stoppen bij }, vereist std::format_error. De format-signatuur moet met de vereiste waardekwalificatie en een const formatter werken zodat ook const waarden onder C++23 formattable zijn; de retouriterator moet het echte uitvoereinde zijn. Specialisatie voor een programmagedefinieerd type is toegestaan, willekeurige vervanging van standaardtypespecialisaties niet. Context en iteratoren leven niet langer dan de aanroep.
Voorbeelden
#include <format>
#include <iostream>
struct Point {
int x;
int y;
};
template<>
struct std::formatter<Point> {
constexpr auto parse(std::format_parse_context& ctx) {
return ctx.begin();
}
auto format(const Point& point, std::format_context& ctx) const {
return std::format_to(ctx.out(), "({}, {})", point.x, point.y);
}
};
int main() {
std::cout << std::format("p={}", Point{3, 4}) << '\n';
}
Resultaat
p=(3, 4)
std::formatter → p=(3, 4)