### Install Meson {fmt} Subproject Source: https://fmt.dev/latest/get-started Install the {fmt} subproject from Meson WrapDB into your project. ```bash meson wrap install fmt ``` -------------------------------- ### Install {fmt} with vcpkg Source: https://fmt.dev/latest/get-started Download, bootstrap, and integrate {fmt} using the vcpkg package manager. This process involves cloning vcpkg, integrating it, and then installing the fmt package. ```bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install fmt ``` -------------------------------- ### Install {fmt} with Conan Source: https://fmt.dev/latest/get-started Download and install {fmt} using the Conan package manager, specifying the conancenter remote and enabling missing builds. ```bash conan install -r conancenter --requires="fmt/[*]" --build=missing ``` -------------------------------- ### Install {fmt} with Homebrew on macOS Source: https://fmt.dev/latest/get-started Install {fmt} on macOS using the Homebrew package manager. ```bash brew install fmt ``` -------------------------------- ### Example of fmt::ptr Source: https://fmt.dev/latest/api Shows how to use fmt::ptr to format a pointer. ```C++ auto s = fmt::format("{}", fmt::ptr(p)); ``` -------------------------------- ### Install {fmt} on Debian/Ubuntu Source: https://fmt.dev/latest/get-started Install the {fmt} development package on Debian-based Linux distributions using the apt package manager. ```bash apt install libfmt-dev ``` -------------------------------- ### Example of fmt::format Source: https://fmt.dev/latest/api Demonstrates basic usage of fmt::format to create a formatted string. ```C++ #include std::string message = fmt::format("The answer is {}.", 42); ``` -------------------------------- ### Simple Format String Examples Source: https://fmt.dev/latest/syntax Illustrates basic usage of format strings with positional and implicit argument referencing. ```text "First, thou shalt count to {0}" // References the first argument ``` ```text "Bring me a {}" // Implicitly references the first argument ``` ```text "From {} to {}" // Same as "From {0} to {1}" ``` -------------------------------- ### Example of fmt::memory_buffer Source: https://fmt.dev/latest/api Demonstrates using fmt::memory_buffer to build a string incrementally. ```C++ auto out = fmt::memory_buffer(); fmt::format_to(std::back_inserter(out), "The answer is {}. ", 42); // The buffer content can be converted to std::string with to_string(out). ``` -------------------------------- ### Install {fmt} with Conda Source: https://fmt.dev/latest/get-started Install {fmt} on Linux, macOS, and Windows using the conda-forge channel of the Conda package manager. ```bash conda install -c conda-forge fmt ``` -------------------------------- ### Example of fmt::group_digits Source: https://fmt.dev/latest/api Shows how to format a large integer with thousands separators. ```C++ fmt::print("{}", fmt::group_digits(12345)); // Output: "12,345" ``` -------------------------------- ### Example of fmt::underlying Source: https://fmt.dev/latest/api Demonstrates formatting the underlying value of an enum. ```C++ enum class color { red, green, blue }; auto s = fmt::format("{}", fmt::underlying(color::red)); // s == "0" ``` -------------------------------- ### Example of fmt::system_error Source: https://fmt.dev/latest/api Shows how to throw a std::system_error with a custom message and the current errno. ```C++ // This throws std::system_error with the description // cannot open file 'madeup': No such file or directory // or similar (system message may vary). const char* filename = "madeup"; FILE* file = fopen(filename, "r"); if (!file) throw fmt::system_error(errno, "cannot open file '{}'", filename); ``` -------------------------------- ### Find Installed {fmt} with CMake Source: https://fmt.dev/latest/get-started Integrate an already installed version of {fmt} into your project by using find_package. This is a common method for managing external libraries. ```cmake find_package(fmt) target_link_libraries( fmt::fmt) ``` -------------------------------- ### Compile-Time Error Example with FMT_STRING Source: https://fmt.dev/latest/api This example demonstrates a compile-time error when using FMT_STRING with an invalid format specifier for a string type. ```cpp // A compile-time error because 'd' is an invalid specifier for strings. std::string s = fmt::format(FMT_STRING("{:d}"), "foo"); ``` -------------------------------- ### Chrono Type 'u' Example Source: https://fmt.dev/latest/syntax Represents the ISO weekday as a decimal number (1-7), where Monday is 1. The modified command `%Ou` produces the locale's alternative representation. ```C++ 'u' | The ISO weekday as a decimal number (1-7), where Monday is 1. The modified command `%Ou` produces the locale's alternative representation. ``` -------------------------------- ### Chrono Type 'M' Example Source: https://fmt.dev/latest/syntax Represents the minute as a decimal number, prefixed with 0 if it's a single digit. The modified command `%OM` produces the locale's alternative representation. ```C++ 'M' | The minute as a decimal number. If the result is a single digit, it is prefixed with 0. The modified command `%OM` produces the locale's alternative representation. ``` -------------------------------- ### Get Argument by ID Source: https://fmt.dev/latest/api Retrieves the argument with the specified ID from the `basic_format_args` view. ```cpp auto get(int id) -> format_arg; ``` -------------------------------- ### Chrono Type 'a', 'A', 'b', 'B' Examples Source: https://fmt.dev/latest/syntax Format specifiers for abbreviated and full weekday and month names. Throws `format_error` if the value is invalid. ```C++ 'a' | The abbreviated weekday name, e.g. "Sat". If the value does not contain a valid weekday, an exception of type `format_error` is thrown. ``` ```C++ 'A' | The full weekday name, e.g. "Saturday". If the value does not contain a valid weekday, an exception of type `format_error` is thrown. ``` ```C++ 'b' | The abbreviated month name, e.g. "Nov". If the value does not contain a valid month, an exception of type `format_error` is thrown. ``` ```C++ 'B' | The full month name, e.g. "November". If the value does not contain a valid month, an exception of type `format_error` is thrown. ``` -------------------------------- ### Chrono Type 'q' and 'Q' Examples Source: https://fmt.dev/latest/syntax Used for formatting durations: 'q' outputs the duration's unit suffix, and 'Q' outputs the duration's numeric value (as if extracted via `.count()`). ```C++ 'q' | The duration's unit suffix. ``` ```C++ 'Q' | The duration's numeric value (as if extracted via `.count()`). ``` -------------------------------- ### Chrono Type 'e' Example Source: https://fmt.dev/latest/syntax Represents the day of the month as a decimal number, prefixed with a space if it's a single digit. The modified command `%Oe` produces the locale's alternative representation. ```C++ 'e' | The day of month as a decimal number. If the result is a single decimal digit, it is prefixed with a space. The modified command `%Oe` produces the locale's alternative representation. ``` -------------------------------- ### Chrono Type 'm' Example Source: https://fmt.dev/latest/syntax Represents the month as a decimal number (Jan is 01), prefixed with 0 if it's a single digit. The modified command `%Om` produces the locale's alternative representation. ```C++ 'm' | The month as a decimal number. Jan is 01. If the result is a single digit, it is prefixed with 0. The modified command `%Om` produces the locale's alternative representation. ``` -------------------------------- ### Chrono Type 'd' Example Source: https://fmt.dev/latest/syntax Represents the day of the month as a decimal number, prefixed with 0 if it's a single digit. The modified command `%Od` produces the locale's alternative representation. ```C++ 'd' | The day of month as a decimal number. If the result is a single decimal digit, it is prefixed with 0. The modified command `%Od` produces the locale's alternative representation. ``` -------------------------------- ### Chrono Type 'c' Example Source: https://fmt.dev/latest/syntax Represents the date and time in a locale-specific format, e.g., "Sat Nov 12 22:04:00 1955". The modified command `%Ec` uses the locale's alternate representation. ```C++ 'c' | The date and time representation, e.g. "Sat Nov 12 22:04:00 1955". The modified command `%Ec` produces the locale's alternate date and time representation. ``` -------------------------------- ### Chrono Type 'S' Example Source: https://fmt.dev/latest/syntax Represents seconds as a decimal number, prefixed with 0 if less than 10. Handles floating-point precision for durations, potentially to microseconds. The modified command `%OS` produces the locale's alternative representation. ```C++ 'S' | Seconds as a decimal number. If the number of seconds is less than 10, the result is prefixed with 0. If the precision of the input cannot be exactly represented with seconds, then the format is a decimal floating-point number with a fixed format and a precision matching that of the precision of the input (or to a microseconds precision if the conversion to floating-point decimal seconds cannot be made within 18 fractional digits). The modified command `%OS` produces the locale's alternative representation. ``` -------------------------------- ### Chrono Type 'x', 'X', 'y', 'Y', 'z', 'Z' Examples Source: https://fmt.dev/latest/syntax Format specifiers for date and time representations. 'x' is locale's appropriate date representation, 'X' is locale's appropriate time representation. 'y' is year without century, 'Y' is year with century. 'z' is time zone offset, 'Z' is time zone name. ```C++ 'x' | The locale's appropriate date representation. The modified command `%Ex` produces the locale's alternate date representation. ``` ```C++ 'X' | The locale's appropriate time representation. The modified command `%EX` produces the locale's alternate time representation. ``` ```C++ 'y' | The year without a century as a decimal number (00-99). If the result is a single decimal digit, it is prefixed with 0. The modified command `%Ey` produces the locale's alternative representation of the year. ``` ```C++ 'Y' | The year as a decimal number. The modified command `%EY` produces the locale's alternative representation of the year. ``` ```C++ 'z' | The time zone offset in the form -hh:mm or +hh:mm. If the time zone cannot be represented, the result is an exception of type `format_error`. ``` ```C++ 'Z' | The time zone name. If the time zone cannot be represented, the result is an exception of type `format_error`. ``` -------------------------------- ### Chrono Type 'g', 'G', 'u', 'U', 'V', 'w', 'W' Examples Source: https://fmt.dev/latest/syntax Format specifiers for ISO week-based year and weekday. 'g' is last two digits of ISO year, 'G' is full ISO year. 'u' is ISO weekday (1-7, Mon=1), 'U' is week number (Sun=1), 'V' is ISO week number, 'w' is weekday (0-6, Sun=0), 'W' is week number (Mon=1). ```C++ 'g' | The last two decimal digits of the ISO week-based year. If the result is a single digit it is prefixed by 0. ``` ```C++ 'G' | The ISO week-based year as a decimal number. If the result is less than four digits it is left-padded with 0 to four digits. ``` ```C++ 'u' | The ISO weekday as a decimal number (1-7), where Monday is 1. The modified command `%Ou` produces the locale's alternative representation. ``` ```C++ 'U' | The week number of the year as a decimal number, with Sunday as the first day of the week (00-53). If the result is a single decimal digit, it is prefixed with 0. ``` ```C++ 'V' | The ISO week number of the year as a decimal number. The week begins on Monday, and is numbered 01 to 53. If the result is a single decimal digit, it is prefixed with 0. ``` ```C++ 'w' | The number of the day of the week as a decimal number (0-6), where Sunday is 0. If the result is a single decimal digit, it is prefixed with 0. ``` ```C++ 'W' | The week number of the year as a decimal number, with Monday as the first day of the week (00-53). If the result is a single decimal digit, it is prefixed with 0. ``` -------------------------------- ### Basic CMake Build Process Source: https://fmt.dev/latest/get-started Create a build directory, navigate into it, and generate native build scripts using CMake. This is the initial step for building the library. ```bash mkdir build cd build cmake .. ``` -------------------------------- ### System APIs - print (to file) Source: https://fmt.dev/latest/api Formats arguments according to specifications in `fmt` and writes the output to the file. ```APIDOC ## print (to file) ### Description Formats `args` according to specifications in `fmt` and writes the output to the file. ### Syntax ```cpp void print(format_string fmt, T&&... args); ``` ``` -------------------------------- ### Configure Meson build for {fmt} Source: https://fmt.dev/latest/get-started Add the {fmt} subproject and retrieve its dependency object in your meson.build file. ```meson fmt = subproject('fmt') fmt_dep = fmt.get_variable('fmt_dep') ``` -------------------------------- ### Meson Build {fmt} as Static Library Source: https://fmt.dev/latest/get-started Configure the {fmt} subproject in Meson to build as a static library by setting the default_library option. ```meson fmt = subproject('fmt', default_options: 'default_library=static') fmt_dep = fmt.get_variable('fmt_dep') ``` -------------------------------- ### Import and Use build2 Target Source: https://fmt.dev/latest/get-started Import the {fmt} library target and use it as a prerequisite for your own targets in the buildfile. ```build2 import fmt = fmt%lib{fmt} lib{mylib} : cxx{**} ... $fmt ``` -------------------------------- ### Build Documentation with Make Source: https://fmt.dev/latest/get-started After generating build scripts with CMake, compile the 'doc' target using make to generate HTML documentation. ```bash make doc ``` -------------------------------- ### Integrate {fmt} with Other Build Systems Source: https://fmt.dev/latest/get-started Manually add {fmt} source files and include directories to your project for use with custom or unsupported build systems. ```c++ #include #include #include ``` -------------------------------- ### Locale-Independent Formatting Source: https://fmt.dev/latest/api By default, formatting is locale-independent. This example shows how to enable locale-specific formatting for number separators. ```cpp #include #include std::locale::global(std::locale("en_US.UTF-8")); auto s = fmt::format("{:L}", 1000000); // s == "1,000,000" ``` -------------------------------- ### Compile-Time Formatted String Source: https://fmt.dev/latest/api Demonstrates using compile-time format string compilation for potentially more efficient binary code. This is recommended when formatting is a performance bottleneck. ```C++ using namespace fmt::literals; std::string s = fmt::format("{}"_cf, point(4, 2)); ``` -------------------------------- ### Chrono Type 'n' and 't' Examples Source: https://fmt.dev/latest/syntax Represents special characters for formatting: 'n' for a newline and 't' for a horizontal tab. ```C++ 'n' | A new-line character. ``` ```C++ 't' | A horizontal-tab character. ``` -------------------------------- ### FetchContent for CMake Integration Source: https://fmt.dev/latest/get-started Use FetchContent to automatically download and integrate {fmt} as a dependency at CMake configure time. Requires CMake 3.11 or later. ```cmake include(FetchContent) FetchContent_Declare( fmt GIT_REPOSITORY https://github.com/fmtlib/fmt GIT_TAG e69e5f977d458f2650bb346dadf2ad30c5320281) # 10.2.1 FetchContent_MakeAvailable(fmt) target_link_libraries( fmt::fmt) ``` -------------------------------- ### Get size of dynamic argument store Source: https://fmt.dev/latest/api The `size()` method returns the current number of elements stored in the dynamic argument store. ```cpp auto size() -> size_t; ``` -------------------------------- ### Format with Arguments Source: https://fmt.dev/latest/api Formats a string view with provided format arguments. ```C++ auto vformat(string_view fmt, format_args args) -> std::string; ``` -------------------------------- ### Chrono Type 'j' Example Source: https://fmt.dev/latest/syntax For durations, represents the number of days without padding. Otherwise, it's the day of the year (Jan 1 is 001), left-padded with 0 to three digits. ```C++ 'j' | If the type being formatted is a specialization of duration, the decimal number of days without padding. Otherwise, the day of the year as a decimal number. Jan 1 is 001. If the result is less than three digits, it is left-padded with 0 to three digits. ``` -------------------------------- ### Meson Build {fmt} as Header-Only Library Source: https://fmt.dev/latest/get-started Configure the {fmt} subproject in Meson to build as a header-only library using the header-only option. ```meson fmt = subproject('fmt', default_options: ['header-only=true']) fmt_dep = fmt.get_variable('fmt_header_only_dep') ``` -------------------------------- ### Converting Numbers to Different Bases Source: https://fmt.dev/latest/syntax Demonstrates converting integers to hexadecimal, octal, and binary formats. Prefixes like '0x', '0', and '0b' can be added. ```C++ fmt::format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); // Result: "int: 42; hex: 2a; oct: 52; bin: 101010" // with 0x or 0 or 0b as prefix: fmt::format("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42); // Result: "int: 42; hex: 0x2a; oct: 052; bin: 0b101010" ``` -------------------------------- ### Construct Basic Format Arguments from Store Source: https://fmt.dev/latest/api Constructs a `basic_format_args` object from a `format_arg_store`. ```cpp constexpr basic_format_args(const store& s); ``` -------------------------------- ### Define Formatter for Custom Enum Source: https://fmt.dev/latest/api Specialize the `fmt::formatter` for a custom enum type to gain full control over parsing and formatting. This example inherits from `formatter` to support string format specifiers. ```cpp // color.h: #include enum class color {red, green, blue}; template <> struct fmt::formatter: formatter { // parse is inherited from formatter. auto format(color c, format_context& ctx) const -> format_context::iterator; }; ``` ```cpp // color.cc: #include "color.h" #include auto fmt::formatter::format(color c, format_context& ctx) const -> format_context::iterator { string_view name = "unknown"; switch (c) { case color::red: name = "red"; break; case color::green: name = "green"; break; case color::blue: name = "blue"; break; } return formatter::format(name, ctx); } ``` -------------------------------- ### Println to file Source: https://fmt.dev/latest/api Formats arguments according to specifications in fmt and writes the output to the specified file followed by a newline. Use this for outputting lines to specific files or streams. ```cpp template void println(FILE* f, format_string fmt, T&&... args); ``` -------------------------------- ### Chrono Type 'H', 'I', 'p' Examples Source: https://fmt.dev/latest/syntax Format specifiers for hours and AM/PM designation. 'H' is 24-hour format, 'I' is 12-hour format, and 'p' denotes AM/PM. Padding with 0 is applied for single digits. ```C++ 'H' | The hour (24-hour clock) as a decimal number. If the result is a single digit, it is prefixed with 0. The modified command `%OH` produces the locale's alternative representation. ``` ```C++ 'I' | The hour (12-hour clock) as a decimal number. If the result is a single digit, it is prefixed with 0. The modified command `%OI` produces the locale's alternative representation. ``` ```C++ 'p' | The AM/PM designations associated with a 12-hour clock. ``` -------------------------------- ### Dynamic Width Formatting Source: https://fmt.dev/latest/syntax Illustrates using a dynamic width for text alignment, where the width is provided as an argument. ```C++ fmt::format("{:<{}}", "left aligned", 30); // Result: "left aligned " ``` -------------------------------- ### Build dynamic format argument lists Source: https://fmt.dev/latest/api Utilize `dynamic_format_arg_store` to construct argument lists dynamically. This store can then be converted to `fmt::basic_format_args` for use with type-erased formatting functions. ```cpp template class dynamic_format_arg_store; void push_back(const T& arg); fmt::dynamic_format_arg_store store; store.push_back(42); store.push_back("abc"); store.push_back(1.5f); std::string result = fmt::vformat("{} and {} and {}", store); ``` -------------------------------- ### Print to file Source: https://fmt.dev/latest/api Formats arguments according to specifications in fmt and writes the output to the specified file. Use this for directing output to specific streams like stderr. ```cpp template void print(FILE* f, format_string fmt, T&&... args); ``` ```cpp fmt::print(stderr, "Don't {}!", "panic"); ``` -------------------------------- ### Dynamic Precision Formatting Source: https://fmt.dev/latest/syntax Demonstrates how to specify a dynamic precision for floating-point numbers, where the precision is provided as an argument. ```C++ fmt::format("{:.{}f}", 3.14, 1); // Result: "3.1" ``` -------------------------------- ### Add build2 Repository Source: https://fmt.dev/latest/get-started Add the cppget.org repository to your build2 configurations or repositories.manifest to access released {fmt} versions. ```build2 : role: prerequisite location: https://pkg.cppget.org/1/stable ``` -------------------------------- ### Chrono Type 'C' Example Source: https://fmt.dev/latest/syntax Represents the year divided by 100 using floored division, e.g., "19". If the result is a single digit, it is prefixed with 0. The modified command `%EC` produces the locale's alternative representation of the century. ```C++ 'C' | The year divided by 100 using floored division, e.g. "19". If the result is a single decimal digit, it is prefixed with 0. The modified command `%EC` produces the locale's alternative representation of the century. ``` -------------------------------- ### Formatting Standard Container Types Source: https://fmt.dev/latest Shows how to format standard C++ containers like std::vector out-of-the-box. The output is a JSON-like representation. ```cpp fmt::print("{}", std::vector{1, 2, 3}); ``` -------------------------------- ### Print to stdout Source: https://fmt.dev/latest/api Formats arguments according to specifications in fmt and writes the output to stdout. Use this for general-purpose output to the console. ```cpp template void print(format_string fmt, T&&... args); ``` ```cpp fmt::print("The answer is {}. ", 42); ``` -------------------------------- ### Type-Specific Formatting for Dates Source: https://fmt.dev/latest/syntax Demonstrates using the fmt/chrono library to format time structures into human-readable date and time strings. ```C++ #include auto t = tm(); t.tm_year = 2010 - 1900; t.tm_mon = 7; t.tm_mday = 4; t.tm_hour = 12; t.tm_min = 15; t.tm_sec = 58; fmt::print("{:%Y-%m-%d %H:%M:%S}", t); // Prints: 2010-08-04 12:15:58 ``` -------------------------------- ### Println to stdout Source: https://fmt.dev/latest/api Formats arguments according to specifications in fmt and writes the output to stdout followed by a newline. This is useful for ensuring output is on its own line. ```cpp template void println(format_string fmt, T&&... args); ``` -------------------------------- ### fmt::println to FILE* Source: https://fmt.dev/latest/api Formats arguments and writes them to a specified file stream, followed by a newline character. This function allows for line-based output to specific files or streams. ```APIDOC ## void println(FILE* f, format_string fmt, T&&... args) ### Description Formats arguments according to the specifications in `fmt` and writes the output to the file `f` followed by a newline. ### Method `println` ### Parameters #### File Stream - **f** (`FILE*`): A pointer to the `FILE` stream to write the output to. #### Format String - **fmt** (`fmt::format_string`): A format string that can be implicitly constructed from a string literal or a `constexpr` string and is checked at compile time in C++20. For runtime format strings, wrap them in `fmt::runtime`. #### Arguments - **args** (T&&...): A variable number of arguments to be formatted. ### Example ```cpp fmt::println(stdout, "Log entry: {}", "Success"); ``` ``` -------------------------------- ### Link Meson Build Target with {fmt} Source: https://fmt.dev/latest/get-started Include the {fmt} dependency object when defining your executable or library target in meson.build. ```meson my_build_target = executable( 'name', 'src/main.cc', dependencies: [fmt_dep]) ``` -------------------------------- ### Accessing Arguments by Position Source: https://fmt.dev/latest/syntax Demonstrates how to access arguments by their index for formatting strings. Indices can be repeated. ```C++ fmt::format("{0}, {1}, {2}", 'a', 'b', 'c'); // Result: "a, b, c" fmt::format("{}, {}, {}", 'a', 'b', 'c'); // Result: "a, b, c" fmt::format("{2}, {1}, {0}", 'a', 'b', 'c'); // Result: "c, b, a" fmt::format("{0}{1}{0}", "abra", "cad"); // arguments' indices can be repeated // Result: "abracadabra" ``` -------------------------------- ### Format a custom date type Source: https://fmt.dev/latest/api Demonstrates how to format a custom date type by specializing fmt::formatter. This allows the library to handle user-defined types seamlessly. ```cpp template <> struct fmt::formatter : ostream_formatter {}; std::string s = fmt::format("The date is {}", date{2012, 12, 9}); // s == "The date is 2012-12-9" ``` -------------------------------- ### System APIs - windows_error Source: https://fmt.dev/latest/api Constructs a `std::system_error` object with a formatted message and the system error description corresponding to the provided Windows error code. ```APIDOC ## windows_error ### Description Constructs a `std::system_error` object with the description of the form `: ` where `` is the formatted message and `` is the system message corresponding to the error code. `error_code` is a Windows error code as given by `GetLastError`. If `error_code` is not a valid error code such as -1, the system message will look like "error -1". ### Syntax ```cpp template auto windows_error(int error_code, string_view message, const T&... args) -> std::system_error; ``` ### Example ```cpp // This throws a system_error with the description // cannot open file 'madeup': The system cannot find the file // specified. // or similar (system message may vary). const char *filename = "madeup"; LPOFSTRUCT of = LPOFSTRUCT(); HFILE file = OpenFile(filename, &of, OF_READ); if (file == HFILE_ERROR) { throw fmt::windows_error(GetLastError(), "cannot open file '{}'", filename); } ``` ``` -------------------------------- ### Aligning Text and Specifying Width Source: https://fmt.dev/latest/syntax Shows how to align text within a specified width using left, right, and center alignment. A fill character can also be specified. ```C++ fmt::format("{:<30}", "left aligned"); // Result: "left aligned " fmt::format("{:>30}", "right aligned"); // Result: " right aligned" fmt::format("{:^30}", "centered"); // Result: " centered " fmt::format("{:*^30}", "centered"); // use '*' as a fill char // Result: "***********centered***********" ``` -------------------------------- ### Basic Format Argument Visitor Source: https://fmt.dev/latest/api Represents a single formatting argument, providing a mechanism to visit its value based on its type. ```cpp template class basic_format_arg; auto visit(Visitor&& vis) -> decltype(vis(0)); ``` -------------------------------- ### Default Range Formatting Source: https://fmt.dev/latest/syntax Demonstrates the default formatting for a vector of integers, enclosed in brackets. ```cpp fmt::print("{}", std::vector{10, 20, 30}); // Output: [10, 20, 30] ``` -------------------------------- ### Declare build2 Dependency Source: https://fmt.dev/latest/get-started Specify the {fmt} package and version in your project's manifest file to declare it as a dependency. ```build2 depends: fmt ~10.0.0 ``` -------------------------------- ### Padded Hex Byte Formatting Source: https://fmt.dev/latest/syntax Shows how to format a hex byte with a prefix, ensuring it always prints two characters, padding with zeros if necessary. ```C++ fmt::format("{:#04x}", 0); // Result: "0x00" ``` -------------------------------- ### Construct Basic Format Arguments from Dynamic List Source: https://fmt.dev/latest/api Constructs a `basic_format_args` object from a dynamic list of arguments, including count and whether named arguments are present. ```cpp constexpr basic_format_args(const format_arg* args, int count, bool has_named); ``` -------------------------------- ### Create Runtime Format String Source: https://fmt.dev/latest/api Creates a runtime format string. This allows for format string checks to occur at runtime instead of compile-time. ```cpp auto runtime(string_view s) -> runtime_format_string<>; // Example: // Check format string at runtime instead of compile-time. fmt::print(fmt::runtime("{:d}"), "I am not a number"); ``` -------------------------------- ### fmt::println to stdout Source: https://fmt.dev/latest/api Formats arguments and writes them to stdout, followed by a newline character. This is convenient for logging or displaying messages that should be on their own line. ```APIDOC ## void println(format_string fmt, T&&... args) ### Description Formats arguments according to the specifications in `fmt` and writes the output to `stdout` followed by a newline. ### Method `println` ### Parameters #### Format String - **fmt** (`fmt::format_string`): A format string that can be implicitly constructed from a string literal or a `constexpr` string and is checked at compile time in C++20. For runtime format strings, wrap them in `fmt::runtime`. #### Arguments - **args** (T&&...): A variable number of arguments to be formatted. ### Example ```cpp fmt::println("Processing complete."); ``` ``` -------------------------------- ### String Presentation Types Source: https://fmt.dev/latest/syntax Lists the available presentation types for string data, including default string format and debug format. ```text Type | Meaning ---|--- 's' | String format. This is the default type for strings and may be omitted. '?' | Debug format. The string is quoted and special characters escaped. none | The same as 's'. ``` -------------------------------- ### Custom Formatting Function with Allocator Source: https://fmt.dev/latest/api Write a formatting function that utilizes a custom allocator for output strings. This involves defining custom string types and buffer types that accept the allocator. ```cpp using custom_string = std::basic_string, custom_allocator>; auto vformat(custom_allocator alloc, fmt::string_view fmt, fmt::format_args args) -> custom_string { auto buf = custom_memory_buffer(alloc); fmt::vformat_to(std::back_inserter(buf), fmt, args); return custom_string(buf.data(), buf.size(), alloc); } template auto format(custom_allocator alloc, fmt::string_view fmt, const Args& ... args) -> custom_string { return vformat(alloc, fmt, fmt::make_format_args(args...)); } ``` -------------------------------- ### Basic String View Implementation Source: https://fmt.dev/latest/api An implementation of `std::basic_string_view` for pre-C++17 environments, providing a subset of the API. This is used for format strings to avoid issues with different `-std` compiler options. ```cpp template class basic_string_view; constexpr basic_string_view(const Char* s, size_t count); basic_string_view(const Char* s); basic_string_view(const S& s); constexpr auto data() -> const Char*; constexpr auto size() -> size_t; ``` -------------------------------- ### fmt::dynamic_format_arg_store Source: https://fmt.dev/latest/api A builder-like API for constructing format argument lists dynamically. It stores arguments and can be converted into fmt::basic_format_args for use with type-erased formatting functions. ```APIDOC ## dynamic_format_arg_store ```cpp template class dynamic_format_arg_store; ``` ### Description A dynamic list of formatting arguments with storage. It can be implicitly converted into `fmt::basic_format_args` for passing into type-erased formatting functions such as `fmt::vformat`. ### Methods #### push_back(const T& arg) Adds an argument into the dynamic store for later passing to a formatting function. Note that custom types and string types (but not string views) are copied into the store dynamically allocating memory if necessary. #### push_back(std::reference_wrapper arg) Adds a reference to the argument into the dynamic store for later passing to a formatting function. #### push_back(const detail::named_arg& arg) Adds named argument into the dynamic store for later passing to a formatting function. `std::reference_wrapper` is supported to avoid copying of the argument. The name is always copied into the store. #### clear() Erase all elements from the store. #### reserve(size_t new_cap, size_t new_cap_named) Reserves space to store at least `new_cap` arguments including `new_cap_named` named arguments. #### size() -> size_t Returns the number of elements in the store. ### Example ```cpp fmt::dynamic_format_arg_store store; store.push_back(42); store.push_back("abc"); store.push_back(1.5f); std::string result = fmt::vformat("{} and {} and {}", store); ``` ``` -------------------------------- ### fmt::print to stdout Source: https://fmt.dev/latest/api Formats arguments according to the format string and writes the output to stdout. Supports compile-time checked format strings via `fmt::format_string`. ```APIDOC ## void print(format_string fmt, T&&... args) ### Description Formats arguments according to the specifications in `fmt` and writes the output to `stdout`. ### Method `print` ### Parameters #### Format String - **fmt** (`fmt::format_string`): A format string that can be implicitly constructed from a string literal or a `constexpr` string and is checked at compile time in C++20. For runtime format strings, wrap them in `fmt::runtime`. #### Arguments - **args** (T&&...): A variable number of arguments to be formatted. ### Example ```cpp fmt::print("The answer is {}.", 42); ``` ``` -------------------------------- ### Format String Source: https://fmt.dev/latest/api Formats arguments according to a format string and returns the result as a std::string. ```C++ template auto format(format_string fmt, T&&... args) -> std::string; ``` -------------------------------- ### Build Shared Library with CMake Source: https://fmt.dev/latest/get-started Configure CMake to build fmt as a shared library by setting the BUILD_SHARED_LIBS variable to TRUE. ```bash cmake -DBUILD_SHARED_LIBS=TRUE .. ``` -------------------------------- ### Buffer Capacity Method Source: https://fmt.dev/latest/api Returns the total capacity of the buffer. ```C++ constexpr auto capacity() -> size_t; ``` -------------------------------- ### Construct Format Argument Store Source: https://fmt.dev/latest/api Constructs an object that stores references to arguments and can be implicitly converted to `format_args`. `Context` can be omitted, defaulting to `context`. Consider `arg` for lifetime management. ```cpp template constexpr auto make_format_args(T&... args) -> detail::format_arg_store; ``` -------------------------------- ### fmt::print to FILE* Source: https://fmt.dev/latest/api Formats arguments according to the format string and writes the output to a specified file stream. This function is useful for directing formatted output to specific files or streams. ```APIDOC ## void print(FILE* f, format_string fmt, T&&... args) ### Description Formats arguments according to the specifications in `fmt` and writes the output to the file `f`. ### Method `print` ### Parameters #### File Stream - **f** (`FILE*`): A pointer to the `FILE` stream to write the output to. #### Format String - **fmt** (`fmt::format_string`): A format string that can be implicitly constructed from a string literal or a `constexpr` string and is checked at compile time in C++20. For runtime format strings, wrap them in `fmt::runtime`. #### Arguments - **args** (T&&...): A variable number of arguments to be formatted. ### Example ```cpp fmt::print(stderr, "Don't {}!", "panic"); ``` ``` -------------------------------- ### Locale-Aware Formatting Functions Source: https://fmt.dev/latest/api The fmt/format.h header provides overloads for formatting functions that accept a locale_ref parameter for locale-aware formatting. ```cpp template auto format(locale_ref loc, format_string fmt, T&&... args) -⁠> std::string; ``` ```cpp template auto format_to(OutputIt out, locale_ref loc, format_string fmt, T&&... args) -⁠> OutputIt; ``` ```cpp template auto formatted_size(locale_ref loc, format_string fmt, T&&... args) -⁠> size_t; ``` -------------------------------- ### Basic Memory Buffer Resize Method Source: https://fmt.dev/latest/api Resizes the buffer to a specified number of elements. New elements may be uninitialized if T is a POD type. ```C++ void resize(size_t count); ``` -------------------------------- ### Reserve space in dynamic argument store Source: https://fmt.dev/latest/api Use `reserve` to pre-allocate space for arguments, potentially improving performance by reducing reallocations. It allows specifying capacity for both regular and named arguments. ```cpp void reserve(size_t new_cap, size_t new_cap_named); ``` -------------------------------- ### Compile-Time Formatting with FMT_STATIC_FORMAT Source: https://fmt.dev/latest/api `FMT_STATIC_FORMAT` allows formatting into a string of the exact required size at compile time. Both the format string and arguments must be compile-time expressions. The result can be accessed via `c_str()` or `str()`. ```APIDOC ## FMT_STATIC_FORMAT ### Description Formats arguments according to the format string `fmt_str` and produces a string of the exact required size at compile time. Both the format string and the arguments must be compile-time expressions. The resulting string can be accessed as a C string via `c_str()` or as a `fmt::string_view` via `str()`. ### Syntax ```cpp FMT_STATIC_FORMAT(fmt_str, ...) ``` ### Example ```cpp // Produces the static string "42" at compile time. static constexpr auto result = FMT_STATIC_FORMAT("{}", 42); const char* s = result.c_str(); ``` ``` -------------------------------- ### fmt::format_to Source: https://fmt.dev/latest/api Formats arguments according to the format string and writes the result to an output iterator. It returns an iterator pointing past the end of the written output. ```APIDOC ## auto format_to(OutputIt&& out, format_string fmt, T&&... args) -> remove_cvref_t ### Description Formats arguments according to specifications in `fmt`, writes the result to the output iterator `out`, and returns the iterator past the end of the output range. `format_to` does not append a terminating null character. ### Method `format_to` ### Parameters #### Output Iterator - **out** (OutputIt&&): An output iterator to write the formatted string to. #### Format String - **fmt** (`fmt::format_string`): A format string that can be implicitly constructed from a string literal or a `constexpr` string and is checked at compile time in C++20. For runtime format strings, wrap them in `fmt::runtime`. #### Arguments - **args** (T&&...): A variable number of arguments to be formatted. ### Return Value - `remove_cvref_t`: An iterator pointing past the end of the written output. ### Example ```cpp auto out = std::vector(); fmt::format_to(std::back_inserter(out), "{}", 42); ``` ``` -------------------------------- ### Basic Format Arguments View Source: https://fmt.dev/latest/api A view of formatting arguments, intended for use as a parameter type in type-erased functions like `vformat` to avoid lifetime issues. Direct instantiation can lead to dangling references. ```cpp template class basic_format_args; void vlog(fmt::string_view fmt, fmt::format_args args); // OK // fmt::format_args args = fmt::make_format_args(); // Dangling reference ``` -------------------------------- ### Compile-Time Formatting with FMT_STATIC_FORMAT Source: https://fmt.dev/latest/api Formats arguments at compile time into a string of the exact required size. Both the format string and arguments must be compile-time expressions. ```C++ static constexpr auto result = FMT_STATIC_FORMAT("{}", 42); const char* s = result.c_str(); ``` -------------------------------- ### Buffer Size Method Source: https://fmt.dev/latest/api Returns the current size of the buffer. ```C++ constexpr auto size() -> size_t; ``` -------------------------------- ### Format Arguments Type Alias Source: https://fmt.dev/latest/api Type alias for `basic_format_args` using the default `context`. ```cpp using format_args = basic_format_args; ``` -------------------------------- ### Calculate formatted size Source: https://fmt.dev/latest/api Returns the number of characters that would be in the output of format(fmt, args...). Use this to pre-allocate buffers. ```cpp template auto formatted_size(format_string fmt, T&&... args) -> size_t; ``` -------------------------------- ### Type-safe printf to string Source: https://fmt.dev/latest/api Format arguments using printf-style syntax and return the result as a std::string. This offers a type-safe alternative to sprintf. ```cpp template auto sprintf(string_view fmt, const T&... args) -> std::string; std::string message = fmt::sprintf("The answer is %d", 42); ``` -------------------------------- ### Creating Text Style with Background Color Source: https://fmt.dev/latest/api Creates a text style object that specifies the background color for terminal output. ```C++ auto bg(detail::color_type background) -> text_style; ``` -------------------------------- ### Creating Text Style with Foreground Color Source: https://fmt.dev/latest/api Creates a text style object that specifies the foreground color for terminal output. ```C++ auto fg(detail::color_type foreground) -> text_style; ``` -------------------------------- ### Custom Logging Function with Compile-Time Checks Source: https://fmt.dev/latest/api Implements a custom logging function with compile-time checks and a small binary footprint. It uses a helper `vlog` function for type erasure and a macro for convenient usage. ```cpp #include void vlog(const char* file, int line, fmt::string_view fmt, fmt::format_args args) { fmt::print("{}: {}: {}", file, line, fmt::vformat(fmt, args)); } template void log(const char* file, int line, fmt::format_string fmt, T&&... args) { vlog(file, line, fmt, fmt::make_format_args(args...)); } #define MY_LOG(fmt, ...) log(__FILE__, __LINE__, fmt, __VA_ARGS__) MY_LOG("invalid squishiness: {}", 42); ``` -------------------------------- ### Formatting User-Defined Types via ostream Source: https://fmt.dev/latest/api Demonstrates how to make user-defined types formattable via std::ostream by specializing fmt::formatter and overloading the insertion operator. Requires fmt/ostream.h. ```C++ #include struct date { int year, month, day; friend std::ostream& operator<<(std::ostream& os, const date& d) { return os << d.year << '-' << d.month << '-' << d.day; } }; ``` -------------------------------- ### Compile-Time Formatting with FMT_COMPILE Source: https://fmt.dev/latest/api Converts a string literal into a format string parsed at compile time, generating efficient formatting code without runtime processing. Requires C++17. ```C++ std::string s = fmt::format(FMT_COMPILE("{}"), 42); ``` -------------------------------- ### Format an initializer list with a custom separator Source: https://fmt.dev/latest/api Use fmt::join to format elements of an std::initializer_list with a specified separator. ```cpp fmt::print("{}", fmt::join({1, 2, 3}, ", ")); // Output: "1, 2, 3" ``` -------------------------------- ### Terminal Colors and Text Styles Source: https://fmt.dev/latest/api The `fmt/color.h` header provides APIs for controlling terminal colors and text styles using ANSI escape sequences. ```APIDOC ## print (colored output) ### Description Formats a string and prints it to stdout using ANSI escape sequences to specify text formatting. ### Syntax ```cpp template void print(text_style ts, format_string fmt, T&&... args); ``` ### Example ```cpp fmt::print(fmt::emphasis::bold | fg(fmt::color::red), "Elapsed time: {0:.2f} seconds", 1.23); ``` ``` ```APIDOC ## fg (foreground color) ### Description Creates a text style from the foreground (text) color. ### Syntax ```cpp auto fg(detail::color_type foreground) -> text_style; ``` ``` ```APIDOC ## bg (background color) ### Description Creates a text style from the background color. ### Syntax ```cpp auto bg(detail::color_type background) -> text_style; ``` ``` ```APIDOC ## styled ### Description Returns an argument that will be formatted using ANSI escape sequences, to be used in a formatting function. ### Syntax ```cpp template auto styled(const T& value, text_style ts) -> detail::styled_arg>; ``` ### Example ```cpp fmt::print("Elapsed time: {0:.2f} seconds", fmt::styled(1.23, fmt::fg(fmt::color::green) | fmt::bg(fmt::color::blue))); ``` ``` -------------------------------- ### User-Defined Formatter for Compile-Time Formatting Source: https://fmt.dev/latest/api Shows how to specialize fmt::formatter for a user-defined type to enable compile-time formatting. The formatter must have a constexpr format method. ```C++ template <> struct fmt::formatter { constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); } template constexpr auto format(const point& p, FormatContext& ctx) const { return format_to(ctx.out(), "({}, { }"_cf, p.x, p.y); } }; constexpr auto s = FMT_STATIC_FORMAT("{}", point(4, 2)); const char* cstr = s.c_str(); // Points the static string "(4, 2)". ```