The Formatting Library in C++20

Today, I will start a series about the formatting library in C++20. The series is based on my C++20 book.

Although Peter Gottschling wrote two great blog posts about the formatting library in C++20 (“std::format in C++20“, “C++20: Extend std::format for User-Defined Types“, I will write about the formatting library again. The reason is simple: Peter’s post gave you a great introduction and overview. I want to present all the details so that you can use this post and the upcoming ones as a reference.

C++20 supports the following formatting functions:

The functions std::format and std::format_to are functionally equivalent to their pendants std::vformat and std::vformat_to, but they differ in a few points:

  • std::format, std::_format_to, and std::format_to_n: They require a compile-time value as a format string. This format string can be a constexpr string or a string literal.
  • std::vformat, and std::vformat_t: It’s format string can be a lvalue. The arguments must be passed to the variadic function std::make_format_args. e.g.: std::vformat(formatString, std::make_format_args(args)).

The formatting functions accept an arbitrary number of arguments. The following program gives a first impression of the functions std::format, std::format_to, and std::format_to_n.

// format.cpp

#include <format>
#include <iostream>
#include <iterator>
#include <string>
 
int main() {
    
    std::cout << '\n';

    std::cout << std::format("Hello, C++{}!\n", "20") << '\n';  // (1)

    std::string buffer;
 
    std::format_to(                                             // (2)
        std::back_inserter(buffer), 
        "Hello, C++{}!\n",          
        "20");    
        
    std::cout << buffer << '\n';

    buffer.clear(); 

    std::format_to_n(                                           // (3)
        std::back_inserter(buffer), 5, 
        "Hello, C++{}!\n",          
        "20");    
        
    std::cout << buffer << '\n';

    
    std::cout << '\n';
   
}

The program directly displays on line (1) the formatted string. However, the calls on lines (2) and (3) use a string as a buffer. Additionally, std::format_to_n pushes only five characters onto the buffer.

Accordingly, here is the corresponding program using std::vformat and std::vformat_n.

// formatRuntime.cpp

#include <format>
#include <iostream>
#include <iterator>
#include <string>
 
int main() {
    
    std::cout << '\n';

    std::string formatString = "Hello, C++{}!\n";

    std::cout << std::vformat(formatString, std::make_format_args("20")) << '\n';  // (1)

    std::string buffer;
 
    std::vformat_to(                                                               // (2)
        std::back_inserter(buffer), 
        formatString,          
        std::make_format_args("20"));    
        
    std::cout << buffer << '\n';
   
}

The formatString in lines (1) and (2) is a lvalue.

Presumably, the most exciting part of the formatting functions is the format string (“Hello, C++{}!\n“).

Format String

The formatting string syntax is identical for the formatting functions std::format, std::format_to, std::format_to_n, std::vformat, and std::vformat_to. I use std::format in my examples.

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    • Syntax: std::format(FormatString, Args)

    The format string FormatString consists of

    • Ordinary characters (except { and })
    • Escape sequences {{ and }} that are replaced by { and }
    • Replacement fields

    A replacement field has the format { }.

    • You can use an argument id and a colon inside the replacement field followed by a format specification. Both components are optional.

    The argument id allows you to specify the index of the arguments in Args. The ids start with 0. When you don’t provide the argument id, the fields are filled in the same order as the arguments are given. Either all replacement fields have to use an argument id or none; i.e., std::format("{}, {}", "Hello", "World") and std::format("{1}, {0}", "World", "Hello") will both compile, but std::format("{1}, {}", "World", "Hello") won’t.  

    std::formatter and its specializations define the format specification for the argument types.

    • Basic types and std::string: based on Python’s format specification
    • Chrono types: I present them in an upcoming post.
    • Other formattable types: User-defined std::formatter specialization. I will present them in an upcoming post.

    The fact that the format strings is a compile time variable, has two interesting consequences: performance and safety.

    Compile Time

    • Performance:  If the format string is checked at compile time, there is nothing to do at run time. Consequentially, the three functions std::format, std::format_to, and std::format_to_n promise excellent performance. The prototype library fmt has a few exciting benchmarks.
    • Safety: Using a wrong format string at compile time causes a compilation error. On the contrary, using a format string at run time with std::vformat or std::vformat_to causes a std::format_error exception.

    What’s Next?

    I will use the next blog post to fill in the theory with practice.

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, Philipp Lenk, Hobsbawm, Charles-Jianye Chen, and Keith Jeffery.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    Standard Seminars (English/German)

    Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

    • C++ – The Core Language
    • C++ – The Standard Library
    • C++ – Compact
    • C++11 and C++14
    • Concurrency with Modern C++
    • Design Pattern and Architectural Pattern with C++
    • Embedded Programming with Modern C++
    • Generic Programming (Templates) with C++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,