- Modern C++ Programming Cookbook
- Marius Bancila
- 870字
- 2021-06-11 18:22:18
Using std::format with user-defined types
The C++20 formatting library is a modern alternative to using printf-like functions or the I/O streams library, which it actually complements. Although the standard provides default formatting for basic types, such as integral and floating-point types, bool, character types, strings, and chrono types, the user can create custom specialization for user-defined types. In this recipe, we will learn how to do that.
Getting ready
You should read the previous recipe, Formatting text with std::format, to familiarize yourself with the formatting library.
In the examples that we'll be showing here, we will use the following class:
struct employee
{
int id;
std::string firstName;
std::string lastName;
};
In the next section, we'll introduce the necessary steps to implement to enable text formatting using std::format() for user-defined types.
How to do it...
To enable formatting using the new formatting library for user-defined types, you must do the following:
- Define a specialization of the std::formatter<T, CharT> class in the std namespace.
- Implement the parse() method to parse the portion of the format string corresponding to the current argument. If the class inherits from another formatter, then this method can be omitted.
- Implement the format() method to format the argument and write the output via format_context.
For the employee class listed here, a formatter that formats employee to the form [42] John Doe (that is [id] firstName lastName) can be implemented as follows:
template <>
struct std::formatter<employee>
{
constexpr auto parse(format_parse_context& ctx)
{
return ctx.begin();
}
auto format(employee const & value, format_context& ctx) {
return std::format_to(ctx.out(),
"[{}] {} {}",
e.id, e.firstName, e.lastName);
}
};
How it works...
The formatting library uses the std::formatter<T, CharT> class template to define formatting rules for a given type. Built-in types, string types, and chrono types have formatters provided by the library. These are implemented as specializations of the std::formatter<T, CharT> class template.
This class has two methods:
- parse(), which takes a single argument of the type std::basic_format_parse_context<CharT> and parses the format's specification for the type T, provided by the parse context. The result of the parsing is supposed to be stored in member fields of the class. If the parsing succeeds, this function should return a value of the type std::basic_format_parse_context<CharT>::iterator, which represents the end of the format specification. If the parsing fails, the function should throw an exception of the type std::format_error to provide details about the error.
- format(), which takes two arguments, the first being the object of the type T to format and the second being a formatting context object of the type std::basic_format_context<OutputIt, CharT>. This function should write the output to ctx.out() according to the desired specifiers (which could be something implicit or the result of parsing the format specification). The function must return a value of the type std::basic_format_context<OutputIt, CharT>::iterator, representing the end of the output.
In the implementation shown here, the parse() function does not do anything other than return an iterator representing the beginning of the format specification. The formatting is always done by printing the employee identifier between square brackets, followed by the first name and the last name, such as in [42] John Doe. An attempt to use a format specifier would result in a runtime exception:
employee e{ 42, "John", "Doe" };
auto s1 = std::format("{}", e); // [42] John Doe
auto s2 = std::format("{:L}", e); // error
If you want your user-defined types to support format specifiers, then you must properly implement the parse() method. To show how this can be done, we will support the L specifier for the employee class. When this specifier is used, the employee is formatted with the identifier in square brackets, followed by the last name, a comma, and then the first name, such as in [42] Doe, John:
template<>
struct std::formatter<employee>
{
bool lexicographic_order = false;
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
auto iter = ctx.begin();
auto get_char = [&]() { return iter != ctx.end() ? *iter : 0; };
if (get_char() == ':') ++iter;
char c = get_char();
switch (c)
{
case '}': return ++iter;
case 'L': lexicographic_order = true; return ++iter;
case '{': return ++iter;
default: throw std::format_error("invalid format");
}
}
template <typename FormatContext>
auto format(employee const& e, FormatContext& ctx)
{
if(lexicographic_order)
return std::format_to(ctx.out(), "[{}] {}, {}",
e.id, e.lastName, e.firstName);
return std::format_to(ctx.out(), "[{}] {} {}",
e.id, e.firstName, e.lastName);
}
};
With this defined, the preceding sample code would work. However, using other format specifiers, such as A, for example, would still throw an exception:
auto s1 = std::format("{}", e); // [42] John Doe
auto s2 = std::format("{:L}", e); // [42] Doe, John
auto s3 = std::format("{:A}", e); // error (invalid format)
If you do not need to parse the format specifier in order to support various options, you could entirely omit the parse() method. However, in order to do so, your std::formatter specialization must derive from another std::formatter class. An implementation is shown here:
template<>
struct fmt::formatter<employee> : fmt::formatter<char const*>
{
template <typename FormatContext>
auto format(employee const& e, FormatContext& ctx)
{
return std::format_to(ctx.out(), "[{}] {} {}",
e.id, e.firstName, e.lastName);
}
};
This specialization for the employee class is equivalent to the first implementation shown earlier in the How to do it... section.
See also
- Formatting text with std::format to get a good introduction to the new C++20 text formatting library
- Clojure Programming Cookbook
- Spring Cloud Alibaba核心技術(shù)與實(shí)戰(zhàn)案例
- Learning Elixir
- INSTANT Sencha Touch
- SAP BusinessObjects Dashboards 4.1 Cookbook
- 深入RabbitMQ
- Python數(shù)據(jù)結(jié)構(gòu)與算法(視頻教學(xué)版)
- 大數(shù)據(jù)分析與應(yīng)用實(shí)戰(zhàn):統(tǒng)計(jì)機(jī)器學(xué)習(xí)之?dāng)?shù)據(jù)導(dǎo)向編程
- C++從入門(mén)到精通(第5版)
- Terraform:多云、混合云環(huán)境下實(shí)現(xiàn)基礎(chǔ)設(shè)施即代碼(第2版)
- C語(yǔ)言程序設(shè)計(jì)
- Python爬蟲(chóng)、數(shù)據(jù)分析與可視化:工具詳解與案例實(shí)戰(zhàn)
- Spring Security Essentials
- Buildbox 2.x Game Development
- Leaflet.js Essentials