C++23: A Modularized Standard Library, std::print and std::println
This post is a cross-post from www.ModernesCpp.com.
The C++23 standard library has very impressive improvements. In this post, I will write about the modularized standard library and the two convenience functions std::print and std::println.
The new “Hello World”
Each programming challenge in a new language starts with the “Hello World” program. Since C++98, this was our starting point:
#include <iostream>
int main() {
std::cout << "Hello World\n";
}
Honestly, you have to skip your old habits in C++23. Here is the current “Hello World program:
import std;
int main() {
std::println("Hello World");
}
Let me analyze the program.
Modularized Standard Library
C++23 supports a modularized standard library. You say import std;, and you get the entire standard library. If you also want the global C functions such as printf, you must use import std.compat;. Here is the corresponding “Hello World” program using printf.
import std.compat;
int main() {
printf("Hello World\n");
}
The modularized standard library has two significant improvements: a significantly improved compilation time and usability.
Significantly improved Compilation Time
Importing the standard library (import std) is literally for free. This means that the compilation times will drop significantly. The first experience numbers state that the complication times became faster by at least a factor of 10. The reason for this improvement is evident. Instead of successively expanding your header files, you import a module. For that reason, there is only one module you have to import only once. So far, only the MSVC compiler supports this C++23 feature: Tutorial: Import the C++ standard library using modules from the command line.
Modernes C++ Mentoring
Be part of my mentoring programs:
"C++20: Get the Details" (start: 11 August 2023)
Stay informed: Subscribe via E-Mail.
?
Usability
Assume you want to use the function std::accumulate. Do you know which header you have to include? Is it <numeric>, <functional>, or <algorithm>. Maybe, this was too easy for you. So what about std::forward, or why does the following program fail to compile?
int main() {
auto list = {1, 2, 3, 4};
}
The {1, 2, 3, 4} is a std::initializer_list<int>.
To use it, you have to include the header <initializer_list>. Of course, this header is automatically included when you use a container like std::vector.
Compare this with an import std; or import std::compat; and you are done. I know from my experience. Not only beginners often fail to use the correct header.
I didn’t know if you recognized it, but my C++23-ish “Hello World” program used a second feature of C++23:
std::print and std::println
The C++23 supports for both functions two overloads:
template< class... Args >
void print( std::FILE* stream,
std::format_string<Args...> fmt, Args&&... args );
template< class... Args >
void print( std::format_string<Args...> fmt, Args&&... args );
template< class... Args >
void println( std::FILE* stream,
std::format_string<Args...> fmt, Args&&... args );
template< class... Args >
void println( std::format_string<Args...> fmt, Args&&... args );
The first difference between std::print and std::println is obvious: std::prinln adds a line break. These are the more interesting points:
Variadic Template
std::print and std::println are variadic templates. Variadic templates are templates that can accept an arbitrary number of arguments. Its arguments are perfectly forwarded. std::print and std::println are the type-safe variant of printf. With printf you must specify the format string; with std::print and std::println you use placeholders in the format string. In general, the compiler deduces the type for the placeholders by applying the rules of std::format in C++20. Consequentially, std::print and std::println in C++23 seem to be syntactic sugar for std::format in C++20. Here is the modified C++23-ish “Hello World” program using std::format.
import std;
int main() {
// std::println("Hello World");
std::cout << std::format("{:}\n", "Hello World");
}
If you want to know more about variadic templates, perfect forwarding, and std::format, read my previous posts:
领英推荐
Unicode Support
I wrote that std::print and std::println in C++23 seem to be syntactic sugar for std::format in C++20. Seem, because std::print and std::println support Unicode. Let me quote the relevant parts from the proposal P2093R14:
Another problem is formatting of Unicode text:
std::cout << "Привет, κ?σμο?!";
If the source and execution encoding is UTF-8 this will produce the expected output on most GNU/Linux and macOS systems. Unfortunately on Windows it is almost guaranteed to produce mojibake despite the fact that the system is fully capable of printing Unicode, for example
╨?╤?╨╕╨▓╨╡╤é ╬║╧?╧a╬╝╬┐╧é!
even when compiled with /utf-8 using Visual C++ ([MSVC-UTF8]). This happens because the terminal assumes code page 437 in this case independently of the execution encoding.
With the proposed paper
std::print("Привет, κ?σμο?!");
will print "Привет, κ?σμο?!" as expected allowing programmers to write Unicode text portably using standard facilities.
Arbitrary Output Stream
Both variants std::print and std:println have an overload that accepts an arbitrary output stream. By default, the output stream is stdout.
There is more to std::format and, consequentially, std::print and std::println in C++23. In C++23, you can format a container of the Standard Template Library.
Formatted Output of a Container
The following program shows how you can directly display a container of the STL. So far, no C++ compiler supports this feature. Only the brand-new Clang compiler with the libc++ instead of the libstdc++ enables me to use this feature partially. In a fully conforming C++23 implementation, I could use std::println instead of std::format.
// formatVector.cpp
#include <format>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<int> myInts{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << std::format("{:}\n", myInts);
std::cout << std::format("{::+}\n", myInts);
std::cout << std::format("{::02x}\n", myInts);
std::cout << std::format("{::b}\n", myInts);
std::cout << '\n';
std::vector<std::string> myStrings{"Only", "for", "testing", "purpose"};
std::cout << std::format("{:}\n", myStrings);
std::cout << std::format("{::.3}\n", myStrings);
}
I use in this example a std::vector<int> and a std::vector<std::string>. Using {:} as a placeholder displays both containers (lines 1 and 2) directly. Using two colons {::} inside the placeholder allows you to format the elements of the std::vector. The format specifier follows the second colon.
The following screenshot shows the output of the program on the Compiler Explorer:
What’s Next?
In my next post about the standard library improvements in C++23, I will present the extended interface of std::optional and the new data type std::expected for error handling.
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, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, 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, and Bhavith C Achar.
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, PVS-Studio, Tipi.build, and Take Up Code
Seminars
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
Bookable
German
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
New
Contact Me
Modernes C++ Mentoring,