User-Defined Formatting in std::format – Part 2 -- Spencer Collyer

logo.pngLast time, we saw how to provide formatting for a simple user-defined class. Spencer Collyer builds on this, showing how to write a formatter for more complicated types.

User-Defined Formatting in std::format – Part 2

by Spencer Collyer

From the article:

In the previous article in this series [Collyer24], I showed how to write a class to format user-defined classes using the std::format library. In this article I will describe how this can be extended to container classes or any other class that holds objects whose type is specified by the user of your class.

A note on the code listings: The code listings in this article have lines labelled with comments like // 1. Where these lines are referred to in the text of this article, it will be as ‘line 1’ for instance, rather than ‘the line labelled // 1’.

Nested formatter objects

The objects created from the formatter template structs are just ordinary C++ objects – there is nothing special about them 1. In particular, there is nothing to stop you including an object of a formatter template type inside one of your user-defined formatter structs.

You might wonder why you would want to do that. One simple case is if you have a templated container class, and want to create a formatter that can output the container in one go, rather than having to write code to iterate over the container and output each value in turn. Having a nested formatter for the contained value type allows you to do this and allow the values to be formatted differently to the default, as the following examples will show. Other uses will no doubt come to mind for your own classes.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.