Specialize std::formatter for the Path Class
Learn to use the specialization of std::formatter for the path class.
We'll cover the following
The path
class is used throughout the filesystem
library to represent a file or directory path. On POSIX-conformant systems, such as macOS and Linux, the path
object uses the char type to represent filenames. On Windows, path
uses wchar_t
. On Windows, cout
and format()
will not display primitive strings of wchar_t
characters. This means there is no simple out-of-the-box way to write code that uses the filesystem
library and is portable across POSIX and Windows.
We could use preprocessor directives to write specific versions of code for Windows. That may be a reasonable solution for some code bases, but for this book, it's messy and does not serve the purpose of simple, portable, reusable recipes.
The elegant solution is to write a C++20 formatter
specialization for the path
class. This allows us to display path
objects simply and portably.
How to do it
In this recipe, we write a formatter
specialization for use with the fs::path
class:
We start with a namespace alias for convenience. All the
filesystem
names are in thestd::filesystem
namespace:
Get hands-on with 1400+ tech skills courses.