官术网_书友最值得收藏!

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
主站蜘蛛池模板: 宜都市| 揭阳市| 洱源县| 青州市| 洞头县| 张掖市| 康定县| 金门县| 民和| 上思县| 富裕县| 江门市| 乌什县| 绩溪县| 湟源县| 大余县| 鹤庆县| 建瓯市| 团风县| 拜城县| 长治市| 乾安县| 商河县| 原阳县| 临武县| 阿拉善盟| 通城县| 仙桃市| 扎囊县| 左贡县| 曲松县| 海南省| 永宁县| 锡林浩特市| 深圳市| 光山县| 龙口市| 绥化市| 金平| 朝阳区| 禄丰县|