-
Book Overview & Buying
-
Table Of Contents
C++ STL Cookbook - Second Edition
By :
C++20 introduced the concept of modules. Modules represent a more compact and efficient alternative to including headers in your code. The promise of the modules feature is that it will eliminate the need for #include headers in most circumstances. For that promise to be fulfilled, the standard library needs to be available as modules. C++23 provides the std module for that purpose. How to do it.
This recipe demonstrates the usage of the std module.
#include <print>
#include <string>
int main() {
std::string whoami {"I'm Spartacus"};
std::println("Hello, World, {}", whoami);
}
When compiled and run, it produces this output:
Hello, World, I'm Spartacus
std module, you no longer need to use the #include directives. Now, our code can look like this:
import std;
int main() {
std::string whoami {"I'm Spartacus"};
std::println("Hello, World, {}", whoami);
}
When compiled and run, this produces the same output:
Hello, World, I'm Spartacus
This feature uses the modules specification, introduced with C++20, to provide the entire C++ Standard Library in one pre-compiled module. Because modules are imported at link time, they do not import any code or symbols that are not directly referenced in the target code. This makes modules both safer and more efficient than #include directives. As a side benefit, using modules also eliminates the need for the cumbersome include guards that are necessary in #include files.
The std module is a powerful feature that can mitigate long lists of STL #include directives:
#include <print>
#include <iostream>
#include <stack>
#include <deque>
#include <map>
#include <string>
#include <utility>
#include <cctype>
#include <cmath>
#include <iterator>
#include <limits>
All of that may now be replaced with one import statement:
import std;
Many traditional #include headers have legacy C Standard Library symbols declared in the global namespace (e.g., printf or puts). The C++23 standard provides an alternative module named std.compat which provides those global namespace declarations. You may use this anywhere you would use the std module:
import std.compat;
Otherwise, both std and std.compat are the same.
As of late 2025, the C++23 std module specification is not yet implemented on some compilers. In fact, some compilers do not yet implement C++20 modules. Therefore, this book and the accompanying examples will continue to use #include headers. I look forward to having more complete implementations in the future.
Change the font size
Change margin width
Change background colour