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

logo.pngWe’ve seen formatting for simple classes and more complicated types. Spencer Collyer finishes his series by showing us how to apply specific formatting to existing classes.

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

by Spencer Collyer

From the article:

In the previous articles in this series [Collyer24a], [Collyer24b] I showed how to write classes to format user-defined classes and container classes using the std::format library.

In this article I will show you how to create format wrappers, special purpose classes that allow you to apply specific formatting to objects of existing classes.

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’.

Format wrappers

I’d now like to introduce a type of class which I call ‘format wrappers’. A format wrapper is a very simple class which wraps a value of another type. They exist purely so that we can define a formatter for the format wrapper. The idea is that the formatter will then output the wrapped value using a specific set of formatting rules. Hopefully this will become clearer when we discuss the Quoted format wrapper later.

A format wrapper is a very simple class, which normally consists of just a constructor taking an object of the wrapped type, and a public member variable holding a copy or reference to that value. They are intended to be used in the argument list of one of std::format’s formatting functions, purely as a way to select the correct formatter.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.