### Install {fmt} using vcpkg Source: https://fmt.dev/12.0/get-started This sequence of commands installs the {fmt} library using the vcpkg package manager. It involves cloning the vcpkg repository, bootstrapping it, integrating it with the system, and then installing {fmt}. ```bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install fmt ``` -------------------------------- ### Meson: Install fmt Subproject Source: https://fmt.dev/12.0/get-started Installs the fmt subproject from WrapDB using Meson. This is the first step to integrate fmt into a Meson-based project. ```bash meson wrap install fmt ``` -------------------------------- ### Install {fmt} on macOS using Homebrew Source: https://fmt.dev/12.0/get-started This command installs the {fmt} library on macOS using the Homebrew package manager. ```bash brew install fmt ``` -------------------------------- ### Install {fmt} using Conan Source: https://fmt.dev/12.0/get-started This command installs the {fmt} library using the Conan package manager. It specifies the conancenter remote and the fmt package, allowing Conan to download and build it if necessary. ```bash conan install -r conancenter --requires="fmt/[*]" --build=missing ``` -------------------------------- ### Install {fmt} using Conda Source: https://fmt.dev/12.0/get-started This command installs the {fmt} library on Linux, macOS, and Windows using the Conda package manager and the conda-forge channel. ```bash conda install -c conda-forge fmt ``` -------------------------------- ### Build {fmt} Documentation with Make Source: https://fmt.dev/12.0/get-started This command builds the documentation for {fmt} after the build system has been generated by CMake. It requires Python, Doxygen, and specific MkDocs packages to be installed. ```bash make doc ``` -------------------------------- ### Install {fmt} on Debian/Ubuntu Source: https://fmt.dev/12.0/get-started This command installs the {fmt} development package on Debian, Ubuntu, and other Debian-based Linux distributions using the `apt` package manager. ```bash apt install libfmt-dev ``` -------------------------------- ### Build {fmt} from Source with CMake Source: https://fmt.dev/12.0/get-started This snippet outlines the initial steps for building {fmt} from source using CMake. It involves creating a build directory, navigating into it, and then running CMake to generate the build scripts. ```bash mkdir build cd build cmake .. ``` -------------------------------- ### Meson: Configure fmt as Header-Only Library Source: https://fmt.dev/12.0/get-started Configures fmt to be built as a header-only library using Meson. This simplifies integration by only requiring header files. ```meson fmt = subproject('fmt', default_options: ['header-only=true']) fmt_dep = fmt.get_variable('fmt_header_only_dep') ``` -------------------------------- ### Manual Integration: C++ Code Source: https://fmt.dev/12.0/get-started Manually integrates the fmt library into a C++ project. This involves including necessary headers and compiling the source file. ```cpp // Add include/fmt to include directories // Compile src/format.cc and link with your code #include int main() { fmt::print("Hello, {}!\n", "world"); return 0; } ``` -------------------------------- ### Integrate {fmt} with CMake using find_package Source: https://fmt.dev/12.0/get-started This snippet demonstrates how to use an already installed version of the {fmt} library with CMake. It uses the `find_package` command to locate the library and then links the `fmt::fmt` target to your project. ```cmake find_package(fmt) target_link_libraries( fmt::fmt) ``` -------------------------------- ### Meson: Link fmt Dependency to Executable Source: https://fmt.dev/12.0/get-started Links the fmt library dependency to an executable build target in Meson. This ensures the fmt library is available at link time. ```meson my_build_target = executable( 'name', 'src/main.cc', dependencies: [fmt_dep]) ``` -------------------------------- ### Meson: Configure fmt as Static Library Source: https://fmt.dev/12.0/get-started Configures fmt to be built as a static library using Meson. This option is useful for embedding the library directly into executables. ```meson fmt = subproject('fmt', default_options: 'default_library=static') mt_dep = fmt.get_variable('fmt_dep') ``` -------------------------------- ### Meson: Configure fmt Subproject in meson.build Source: https://fmt.dev/12.0/get-started Configures the fmt subproject within a Meson build. It retrieves the fmt dependency for linking into build targets. ```meson fmt = subproject('fmt') fmt_dep = fmt.get_variable('fmt_dep') ``` -------------------------------- ### Build {fmt} Shared Library with CMake Source: https://fmt.dev/12.0/get-started This command configures the CMake build to create a shared library for {fmt}. It sets the `BUILD_SHARED_LIBS` CMake variable to `TRUE`. ```bash cmake -DBUILD_SHARED_LIBS=TRUE .. ``` -------------------------------- ### Integrate {fmt} with CMake using add_subdirectory Source: https://fmt.dev/12.0/get-started This snippet shows how to integrate the {fmt} source tree directly into your CMake project. It uses `add_subdirectory` to include the {fmt} source and then links the `fmt::fmt` target to your project. ```cmake add_subdirectory(fmt) target_link_libraries( fmt::fmt) ``` -------------------------------- ### Configure build2 Project to Depend on {fmt} Source: https://fmt.dev/12.0/get-started This snippet shows how to configure a build2 project to depend on the {fmt} library. It involves specifying the repository in `repositories.manifest`, adding {fmt} as a dependency in the `manifest` file, and importing the library target in the `buildfile`. ```build2 // repositories.manifest // Add one of the repositories to your configurations, or in your repositories.manifest, if not already there: // https://pkg.cppget.org/1/stable // Or // https://github.com/build2-packaging/fmt // manifest depends: fmt ~10.0.0 // buildfile import fmt = fmt%lib{fmt} lib{mylib} : cxx{**} ... $fmt ``` -------------------------------- ### Integrate {fmt} with CMake using FetchContent Source: https://fmt.dev/12.0/get-started This snippet shows how to automatically download and integrate the {fmt} library into your CMake project using the FetchContent module. It requires CMake version 3.11 or higher. The code declares the {fmt} repository and tag, makes it available, and links the `fmt::fmt` target to your project's target. ```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) ``` -------------------------------- ### Build {fmt} Static PIC Library with CMake Source: https://fmt.dev/12.0/get-started This command configures the CMake build to create a static library with position-independent code (PIC) for {fmt}. This is useful for linking into shared libraries. It sets the `CMAKE_POSITION_INDEPENDENT_CODE` CMake variable to `TRUE`. ```bash cmake -DCMAKE_POSITION_INDEPENDENT_CODE=TRUE .. ``` -------------------------------- ### C++ fmtlib: Basic Replacement Field Examples Source: https://fmt.dev/12.0/syntax Demonstrates simple format string syntax with replacement fields in C++. It shows how to reference arguments by index and implicitly. This syntax is used with functions like fmt::format and fmt::print. ```cpp fmt::format("First, thou shalt count to {0}", 10); // References the first argument fmt::format("Bring me a {}", "apple"); // Implicitly references the first argument fmt::format("From {} to {}", 10, 20); // Same as "From {0} to {1}" ``` -------------------------------- ### Padded Hex Byte Formatting - fmt Source: https://fmt.dev/12.0/syntax An example of formatting a hex byte with padding and a prefix, ensuring both hex characters are always printed. This is useful for consistent byte representation. ```cpp fmt::format("{:#04x}", 0); // Result: "0x00" ``` -------------------------------- ### Formatting Standard C++ Containers with FMT Source: https://fmt.dev/12.0/index This example shows FMT's out-of-the-box support for formatting standard C++ types, including containers like std::vector. The output is presented in a human-readable, JSON-like format, demonstrating the library's extensibility. ```cpp fmt::print("{}", std::vector{1, 2, 3}); ``` -------------------------------- ### Format std::chrono::duration and std::chrono::time_point with fmt/chrono.h Source: https://fmt.dev/12.0/api This snippet demonstrates formatting std::chrono::duration and std::chrono::time_point objects using the fmt/chrono.h header. It shows how to print dates, times, and durations in various formats, including strftime-like specifications. The examples cover basic time point formatting and duration formatting. ```cpp #include #include int main() { auto now = std::chrono::system_clock::now(); fmt::print("The date is {:%Y-%m-%d}.\n", now); // Output: The date is 2020-11-07. // (with 2020-11-07 replaced by the current date) using namespace std::literals::chrono_literals; fmt::print("Default format: {} {}\\n", 42s, 100ms); // Output: Default format: 42s 100ms fmt::print("strftime-like format: {:%H:%M:%S}\\n", 3h + 15min + 30s); // Output: strftime-like format: 03:15:30 } ``` -------------------------------- ### Format Hierarchy with formatter Specialization Source: https://fmt.dev/12.0/api This example demonstrates formatting a hierarchy of classes (`A` and `B`) by specializing `fmt::formatter` for a base class `A` with a template that enables it for types derived from `A`. The specialization formats the object by calling its `name()` method, effectively formatting derived types using the base class formatter. ```cpp // demo.h: #include #include struct A { virtual ~A() {} virtual std::string name() const { return "A"; } }; struct B : A { virtual std::string name() const { return "B"; } }; template struct fmt::formatter, char>> : fmt::formatter { auto format(const A& a, format_context& ctx) const { return formatter::format(a.name(), ctx); } }; ``` ```cpp // demo.cc: #include "demo.h" #include int main() { B b; A& a = b; fmt::print("{}", a); // Output: B } ``` -------------------------------- ### Format User-Defined Enum with formatter Specialization Source: https://fmt.dev/12.0/api This example shows how to specialize the `fmt::formatter` for a user-defined `color` enum. It inherits from `formatter` to reuse its parsing capabilities and implements a custom `format` method to map enum values to their string representations. The `color.h` file declares the specialization, and `color.cc` provides the implementation. ```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); } ``` -------------------------------- ### Format std::variant with fmt/std.h Source: https://fmt.dev/12.0/api This snippet shows how to format std::variant objects using the fmt/std.h header. It requires the __cpp_lib_variant library feature. The examples demonstrate formatting a variant containing a char and a variant containing monostate. ```cpp #include #include fmt::print("{}", std::variant('x')); // Output: variant('x') fmt::print("{}", std::variant()); // Output: variant(monostate) ``` -------------------------------- ### Format User-Defined Enum with format_as Source: https://fmt.dev/12.0/api This example demonstrates how to make a user-defined enum class `film` formattable by providing a `format_as` function. The `format_as` function returns the underlying integer value of the enum, which is then formatted by fmt. It should be defined in the same namespace as the type. ```cpp #include namespace kevin_namespacy { enum class film { house_of_cards, american_beauty, se7en = 7 }; auto format_as(film f) { return fmt::underlying(f); } } // namespace kevin_namespacy int main() { fmt::print("{}\n", kevin_namespacy::film::se7en); // Output: 7 } ``` -------------------------------- ### Example of FMT_STRING Compile-Time Error Source: https://fmt.dev/12.0/api Illustrates how `FMT_STRING` catches compile-time errors, such as using an invalid format specifier for a given type. In this case, `{:d}` is invalid for a string. ```c++ // A compile-time error because 'd' is an invalid specifier for strings. std::string s = fmt::format(FMT_STRING("{:d}"), "foo"); ``` -------------------------------- ### Converting Values to Different Bases - fmt Source: https://fmt.dev/12.0/syntax Shows how to convert integers to different bases (decimal, hex, octal, binary) using format specifiers and how to include base prefixes (0x, 0, 0b). ```cpp 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" ``` -------------------------------- ### Dynamic Width Formatting - fmt Source: https://fmt.dev/12.0/syntax Illustrates how to use dynamic width for text alignment by providing the width as an argument. This allows for flexible formatting based on runtime values. ```cpp fmt::format("{:<{}}", "left aligned", 30); // Result: "left aligned " ``` -------------------------------- ### Aligning Text and Specifying Width - fmt Source: https://fmt.dev/12.0/syntax Shows how to align text (left, right, center) within a specified width and how to use a custom fill character. This is useful for creating aligned output. ```cpp 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***********" ``` -------------------------------- ### Dynamic Precision Formatting - fmt Source: https://fmt.dev/12.0/syntax Demonstrates dynamic precision for floating-point numbers, where the precision is specified by an argument. This enables control over the number of decimal places at runtime. ```cpp fmt::format("{:.{}f}", 3.14, 1); // Result: "3.1" ``` -------------------------------- ### fmt Library: Range Format Specifications Source: https://fmt.dev/12.0/syntax Demonstrates how to format ranges of elements using the fmt library. It covers default formatting, string formatting, and debug string formatting for character types, as well as specifying underlying formatters for element types. ```cpp fmt::print("{}", std::vector{10, 20, 30}); // Output: [10, 20, 30] fmt::print("{::#x}", std::vector{10, 20, 30}); // Output: [0xa, 0x14, 0x1e] fmt::print("{}", std::vector{'h', 'e', 'l', 'l', 'o'}); // Output: ['h', 'e', 'l', 'l', 'o'] fmt::print("{:n}", std::vector{'h', 'e', 'l', 'l', 'o'}); // Output: 'h', 'e', 'l', 'l', 'o' fmt::print("{:s}", std::vector{'h', 'e', 'l', 'l', 'o'}); // Output: "hello" fmt::print("{:?s}", std::vector{'h', 'e', 'l', 'l', 'o', '\n'}); // Output: "hello\n" fmt::print("{::}", std::vector{'h', 'e', 'l', 'l', 'o'}); // Output: [h, e, l, l, o] fmt::print("{::d}", std::vector{'h', 'e', 'l', 'l', 'o'}); // Output: [104, 101, 108, 108, 111] ``` -------------------------------- ### Box Drawing with Unicode Fill - fmt Source: https://fmt.dev/12.0/syntax Demonstrates creating a box drawing using Unicode characters for borders and filling the content area with specified alignment and fill character. This utilizes advanced formatting for UI elements. ```cpp fmt::print( "┌{0:─^{2}}┐\n" "│{1: ^{2}}│\n" "└{0:─^{2}}┘\n", "", "Hello, world!", 20); ``` -------------------------------- ### FMT Named Argument Creation (C++) Source: https://fmt.dev/12.0/api Shows how to create named arguments using `fmt::arg` for use in formatting functions. This allows for more readable and maintainable format strings, though it's noted that named arguments are not currently supported for compile-time checks. ```cpp template auto arg(const Char* name, const T& arg) -> detail::named_arg; // Example usage: // fmt::print("The answer is {answer}.\n", fmt::arg("answer", 42)); ``` -------------------------------- ### Format Specification Syntax Source: https://fmt.dev/12.0/syntax Defines the general structure of a standard format specifier. It includes optional components like fill, align, sign, width, precision, and type. The syntax allows for integer or argument-based width and precision. ```bnf format_spec ::= [[fill]align][sign]["#"]["0"][width]["." precision]["L"][type] fill ::= align ::= "<" | ">" | "^" sign ::= "+" | "-" | " " width ::= integer | "{" [arg_id] "}" precision ::= integer | "{" [arg_id] "}" type ::= "a" | "A" | "b" | "B" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "o" | "p" | "s" | "x" | "X" | "?" ``` -------------------------------- ### Base API - Print to stdout Source: https://fmt.dev/12.0/api Formats arguments according to the format string and writes the output to stdout. ```APIDOC ## void print(format_string fmt, T&&... args) ### Description Formats arguments according to the format string and writes the output to stdout. ### Method void ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp fmt::print("The answer is {}.", 42); ``` ### Response #### Success Response (void) N/A #### Response Example N/A ``` -------------------------------- ### Format Specification Sign Options Source: https://fmt.dev/12.0/syntax Details the sign options available for numeric types. '+' for always showing a sign, '-' for only negative signs (default), and a space for a leading space on non-negative numbers. ```text Option | Meaning ---|--- '+' | Indicates that a sign should be used for both nonnegative as well as negative numbers. '-' | Indicates that a sign should be used only for negative numbers (this is the default behavior). space | Indicates that a leading space should be used on nonnegative numbers, and a minus sign on negative numbers. ``` -------------------------------- ### Base API - format_to Source: https://fmt.dev/12.0/api Formats arguments according to the format string and writes the result to the specified output iterator. ```APIDOC ## auto format_to(OutputIt&& out, format_string fmt, T&&... args) -> remove_cvref_t ### Description Formats arguments according to the format string, writes the result to the output iterator `out`, and returns the iterator past the end of the output range. Does not append a null terminator. ### Method auto ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp auto out = std::vector(); fmt::format_to(std::back_inserter(out), "{}", 42); ``` ### Response #### Success Response (Output Iterator) - **OutputIt** (OutputIterator) - An iterator pointing past the end of the written output. #### Response Example N/A ``` -------------------------------- ### Range Joining View Constructor (Initializer List) Source: https://fmt.dev/12.0/api Provides a `join_view` for `std::initializer_list`. This overload allows direct formatting of braced-init-lists with a custom separator. ```c++ template auto join(std::initializer_list list, string_view sep) -> join_view; // Example: fmt::print("{}", fmt::join({1, 2, 3}, ", ")); // Output: "1, 2, 3" ``` -------------------------------- ### Accessing Arguments by Position - fmt Source: https://fmt.dev/12.0/syntax Demonstrates how to access arguments by their position in the format string, including repeating arguments. This feature allows for flexible ordering and reuse of arguments. ```cpp 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" ``` -------------------------------- ### Base API - Println to stdout Source: https://fmt.dev/12.0/api Formats arguments according to the format string and writes the output to stdout, followed by a newline. ```APIDOC ## void println(format_string fmt, T&&... args) ### Description Formats arguments according to the format string and writes the output to stdout, followed by a newline. ### Method void ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp fmt::println("Hello, world!"); ``` ### Response #### Success Response (void) N/A #### Response Example N/A ``` -------------------------------- ### Format Specification Alignment Options Source: https://fmt.dev/12.0/syntax Describes the alignment options within a format specifier. '<' for left-alignment, '>' for right-alignment, and '^' for center-alignment. These options are applied within the specified field width. ```text Option | Meaning ---|--- '<' | Forces the field to be left-aligned within the available space (this is the default for most objects). '>' | Forces the field to be right-aligned within the available space (this is the default for numbers). '^' | Forces the field to be centered within the available space. ``` -------------------------------- ### Base API - Println to file Source: https://fmt.dev/12.0/api Formats arguments according to the format string and writes the output to a specified file stream, followed by a newline. ```APIDOC ## void println(FILE* f, format_string fmt, T&&... args) ### Description Formats arguments according to the format string and writes the output to the specified file stream, followed by a newline. ### Method void ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp fmt::println(stdout, "Processing complete."); ``` ### Response #### Success Response (void) N/A #### Response Example N/A ``` -------------------------------- ### Base API - Print to file Source: https://fmt.dev/12.0/api Formats arguments according to the format string and writes the output to a specified file stream. ```APIDOC ## void print(FILE* f, format_string fmt, T&&... args) ### Description Formats arguments according to the format string and writes the output to the specified file stream. ### Method void ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp fmt::print(stderr, "Don't {}!", "panic"); ``` ### Response #### Success Response (void) N/A #### Response Example N/A ``` -------------------------------- ### Format String with Arguments Source: https://fmt.dev/12.0/api Formats a given string specification with provided arguments and returns the result as a std::string. It utilizes variadic templates for flexible argument handling. ```cpp template auto format(format_string fmt, T&&... args) -> std::string; ``` ```cpp #include std::string message = fmt::format("The answer is {}.", 42); ``` -------------------------------- ### Locale-Aware Formatting with fmt::format Source: https://fmt.dev/12.0/api Demonstrates locale-aware number formatting using the 'L' format specifier. It requires including the `` header and setting the global locale. ```c++ #include #include std::locale::global(std::locale("en_US.UTF-8")); auto s = fmt::format("{:L}", 1000000); // s == "1,000,000" ``` -------------------------------- ### Printing with Terminal Colors and Styles Source: https://fmt.dev/12.0/api Provides functions to format strings and print them to stdout with ANSI escape sequences for text formatting, including colors and styles. Allows defining text styles using foreground and background colors. ```cpp template void print(text_style ts, format_string fmt, T&&... args); ``` ```cpp fmt::print(fmt::emphasis::bold | fg(fmt::color::red), "Elapsed time: {0:.2f} seconds", 1.23); ``` ```cpp auto fg(detail::color_type foreground) -⁠> text_style; ``` ```cpp auto bg(detail::color_type background) -⁠> text_style; ``` ```cpp template auto styled(const T& value, text_style ts) -> detail::styled_arg>; ``` ```cpp fmt::print("Elapsed time: {0:.2f} seconds", fmt::styled(1.23, fmt::fg(fmt::color::green) | fmt::bg(fmt::color::blue))); ``` -------------------------------- ### Formatting with Custom Allocators (vformat) Source: https://fmt.dev/12.0/api Implements a low-level formatting function that takes a custom allocator and returns a string formatted using that allocator. It handles the allocation and construction of the resulting string. ```c++ 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); } ``` -------------------------------- ### FMT Argument Store Construction (C++) Source: https://fmt.dev/12.0/api Demonstrates the construction of `format_arg_store`, which holds formatting arguments for type-erased functions. This is crucial for passing arguments efficiently and safely to functions like `vformat`. ```cpp template constexpr auto make_format_args(T&... args) -> detail::format_arg_store; template class basic_format_args; constexpr basic_format_args(const store& s); constexpr basic_format_args(const format_arg* args, int count, bool has_named); auto get(int id) -> format_arg; using format_args = basic_format_args; ``` -------------------------------- ### FMT Basic String View Implementation (C++) Source: https://fmt.dev/12.0/api Provides a `basic_string_view` implementation compatible with pre-C++17 standards, used internally by FMT for format strings. This ensures consistent behavior across different compiler standards and avoids potential issues with mismatched library compilations. ```cpp template class basic_string_view { public: 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 -> const Char*; constexpr auto size() const -> size_t; }; using string_view = basic_string_view; ``` -------------------------------- ### Base API - format_to_n Source: https://fmt.dev/12.0/api Formats arguments, writes up to 'n' characters to an output iterator, and returns the result information. ```APIDOC ## auto format_to_n(OutputIt out, size_t n, format_string fmt, T&&... args) -> format_to_n_result ### Description Formats arguments, writes up to `n` characters of the result to the output iterator `out`, and returns a structure containing the total output size and the iterator past the end of the output range. Does not append a null terminator. ### Method auto ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp // Example usage would involve defining OutputIt and format_to_n_result ``` ### Response #### Success Response (format_to_n_result) - **OutputIt out** (OutputIterator) - Iterator past the end of the output range. - **size_t size** (size_t) - Total (not truncated) output size. #### Response Example ```json { "out": "", "size": "" } ``` ``` -------------------------------- ### C++ fmt::print to stdout Source: https://fmt.dev/12.0/api Formats arguments according to the format string and writes the output to standard output. It uses C++20 compile-time checks for format strings when possible. Supports various types for formatting. ```cpp template void print(format_string fmt, T&&... args); // Example: // fmt::print("The answer is {}.", 42); ``` -------------------------------- ### C++: Dynamic Format Argument Store - Copying Arguments Source: https://fmt.dev/12.0/api A dynamic list for storing formatting arguments, allowing arguments to be copied into the store. Custom types and strings are copied, potentially involving dynamic memory allocation. ```C++ #include #include template class dynamic_format_arg_store; void push_back(const T& arg); // Example: // 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); ``` -------------------------------- ### C++: Dynamic Format Argument Store - Utility Functions Source: https://fmt.dev/12.0/api Provides utility functions for the dynamic argument store, including clearing all elements, reserving space for arguments, and retrieving the current size. ```C++ #include void clear(); void reserve(size_t new_cap, size_t new_cap_named); auto size() -> size_t; // Example usage would involve calling these methods on a dynamic_format_arg_store object. ``` -------------------------------- ### Formatting Ranges with fmt::join Source: https://fmt.dev/12.0/api Illustrates formatting a `std::vector` using `fmt::join` with a comma and space as a separator. It shows how to apply format specifiers to the joined elements. ```c++ #include auto v = std::vector{1, 2, 3}; fmt::print("{}", fmt::join(v, ", ")); // Output: 1, 2, 3 fmt::print("{:02}", fmt::join(v, ", ")); // Output: 01, 02, 03 ``` -------------------------------- ### Formatting Time Structures - fmt/chrono Source: https://fmt.dev/12.0/syntax Shows how to format `std::tm` structures using the `fmt/chrono.h` extension. It covers common date and time format specifiers like %Y, %m, %d, %H, %M, %S. ```cpp #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 ``` -------------------------------- ### Chrono Format Specification Syntax Source: https://fmt.dev/12.0/syntax Defines the general syntax for chrono formatting specifications. It includes optional fill, alignment, width, precision, and a sequence of conversion specifiers or literal characters. Precision is only applicable to floating-point duration types. ```bnf chrono_format_spec ::= [[fill]align][width]["." precision][chrono_specs] chrono_specs ::= conversion_spec | chrono_specs (conversion_spec | literal_char) conversion_spec ::= "%" [padding_modifier] [locale_modifier] chrono_type literal_char ::= padding_modifier ::= "-" | "_" | "0" locale_modifier ::= "E" | "O" chrono_type ::= "a" | "A" | "b" | "B" | "c" | "C" | "d" | "D" | "e" | "F" | "g" | "G" | "h" | "H" | "I" | "j" | "m" | "M" | "n" | "p" | "q" | "Q" | "r" | "R" | "S" | "t" | "T" | "u" | "U" | "V" | "w" | "W" | "x" | "X" | "y" | "Y" | "z" | "Z" | "%" ``` -------------------------------- ### Format Arguments Source: https://fmt.dev/12.0/api Formats a string view with a set of format arguments. This function is useful for scenarios where format arguments are already packed into a format_args structure. ```cpp auto vformat(string_view fmt, format_args args) -> std::string; ``` -------------------------------- ### Joining Tuple Elements with fmt::join Source: https://fmt.dev/12.0/api Demonstrates using `fmt::join` to format elements of a tuple with a specified separator. This allows for custom string representations of tuple contents. ```c++ #include auto t = std::tuple{1, 'a'}; fmt::print("{}", fmt::join(t, ", ")); // Output: 1, a ``` -------------------------------- ### Compile-Time Formatting with FMT_COMPILE and _cf Source: https://fmt.dev/12.0/api Enables format string parsing, checking, and efficient code generation at compile-time using FMT_COMPILE macro or _cf user-defined literal. Supports built-in and string types, as well as custom types with format methods. This can lead to more binary code and is recommended for performance bottlenecks. ```cpp struct point { double x; double y; }; template <> struct fmt::formatter { constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); } template auto format(const point& p, FormatContext& ctx) const { return format_to(ctx.out(), "({}, {})_cf", p.x, p.y); } }; using namespace fmt::literals; std::string s = fmt::format("{}"_cf, point(4, 2)); ``` ```cpp template constexpr auto operator""_cf(); ``` ```cpp FMT_COMPILE(s) ``` ```cpp // Converts 42 into std::string using the most efficient method and no // runtime format string processing. std::string s = fmt::format(FMT_COMPILE("{}"), 42); ``` -------------------------------- ### Using Locale for Thousands Separator - fmt/format Source: https://fmt.dev/12.0/syntax Illustrates formatting numbers with locale-specific separators, such as the comma for thousands in the US locale. This requires including `` and setting a locale. ```cpp #include auto s = fmt::format(std::locale("en_US.UTF-8"), "{:L}", 1234567890); // s == "1,234,567,890" ``` -------------------------------- ### Formatting with Custom Allocators (format) Source: https://fmt.dev/12.0/api A variadic template function for formatting arguments into a custom string type using a specified allocator. It simplifies the process of formatting by utilizing the `vformat` function. ```c++ template auto format(custom_allocator alloc, fmt::string_view fmt, const Args& ... args) -> custom_string { return vformat(alloc, fmt, fmt::make_format_args(args...)); } ``` -------------------------------- ### Format Specification Type Options for Strings Source: https://fmt.dev/12.0/syntax Lists the type specifiers applicable to string formatting. 's' for standard string representation (default) and '?' for debug format, which quotes the string and escapes special characters. ```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'. ``` -------------------------------- ### Formatting Tuples with fmt/ranges.h Source: https://fmt.dev/12.0/api Shows how to format `std::tuple` objects using the `fmt/ranges.h` header. It provides a convenient way to print tuple contents. ```c++ #include fmt::print("{}", std::tuple{'a', 42}); // Output: ('a', 42) ``` -------------------------------- ### Specifying Sign and Replacing printf Specifiers - fmt Source: https://fmt.dev/12.0/syntax Explains how to specify the sign for numbers (always show, space for positive, only minus) and replaces printf specifiers like %+f, %-f, % f. This provides explicit control over number sign display. ```cpp fmt::format("{:+f}; {:+f}", 3.14, -3.14); // show it always // Result: "+3.140000; -3.140000" fmt::format("{: f}; {: f}", 3.14, -3.14); // show a space for positive numbers // Result: " 3.140000; -3.140000" fmt::format("{:-f}; {:-f}", 3.14, -3.14); // show only the minus -- same as '{:f}; {:f}' // Result: "3.140000; -3.140000" ``` -------------------------------- ### C++ fmt::println to FILE* Source: https://fmt.dev/12.0/api Formats arguments according to the format string and writes the output to a specified file stream, followed by a newline character. This function allows for line-buffered output to specific file streams. ```cpp template void println(FILE* f, format_string fmt, T&&... args); ``` -------------------------------- ### Compile-Time Formatting with FMT_STATIC_FORMAT Source: https://fmt.dev/12.0/api Supports formatting into a string of the exact required size at compile time. Requires both the format string and arguments to be compile-time expressions. The result can be accessed as a C string via c_str() or as a fmt::string_view via str(). ```cpp 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)". ``` ```cpp FMT_STATIC_FORMAT(fmt_str, ...) ``` ```cpp // Produces the static string "42" at compile time. static constexpr auto result = FMT_STATIC_FORMAT("{}", 42); const char* s = result.c_str(); ``` -------------------------------- ### C++ fmt::println to stdout Source: https://fmt.dev/12.0/api Formats arguments according to the format string and writes the output to standard output, followed by a newline character. This is convenient for printing messages that should be on their own line. ```cpp template void println(format_string fmt, T&&... args); ``` -------------------------------- ### Range Joining View Constructor (Iterators) Source: https://fmt.dev/12.0/api Defines a `join_view` that formats elements from an iterator range `[begin, end)` with a specified separator. This overload is flexible for various container types. ```c++ template auto join(It begin, Sentinel end, string_view sep) -> join_view; ``` -------------------------------- ### C++ fmt::print to FILE* Source: https://fmt.dev/12.0/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 like stderr. It takes a FILE* pointer as the first argument. ```cpp template void print(FILE* f, format_string fmt, T&&... args); // Example: // fmt::print(stderr, "Don't {}!", "panic"); ``` -------------------------------- ### Unicode Text Output with FMT Source: https://fmt.dev/12.0/index This snippet illustrates FMT's portable Unicode support, enabling correct printing of non-ASCII characters across different operating systems and consoles. It emphasizes the library's ability to handle UTF-8 and char strings reliably. ```cpp fmt::print("Слава Україні!"); ``` -------------------------------- ### Format Specification Type Options for Characters Source: https://fmt.dev/12.0/syntax Specifies the type option for character formatting. 'c' represents the character format, which is the default and can be omitted. ```text Type | Meaning ---|--- 'c' | Character format. This is the default type for characters and may be omitted. ``` -------------------------------- ### Locale-Aware Formatting Functions Overloads Source: https://fmt.dev/12.0/api Provides overloads for `format`, `format_to`, and `formatted_size` that accept a `locale_ref` parameter. This allows for locale-specific formatting without incurring the overhead of including the `` header by default. ```c++ template auto format(locale_ref loc, format_string fmt, T&&... args) -> std::string; ``` ```c++ template auto format_to(OutputIt out, locale_ref loc, format_string fmt, T&&... args) -> OutputIt; ``` ```c++ template auto formatted_size(locale_ref loc, format_string fmt, T&&... args) -> size_t; ``` -------------------------------- ### C++: Formatting Values via ostream operator<< Source: https://fmt.dev/12.0/api Returns a view that formats a given value using its overloaded ostream operator<<. ```C++ #include #include template constexpr auto streamed(const T& value) -> detail::streamed_view; // Example: // fmt::print("Current thread id: \n", // fmt::streamed(std::this_thread::get_id())); ``` -------------------------------- ### Format System Error Message to Buffer Source: https://fmt.dev/12.0/api Formats an error message for an operating system or runtime error and writes it to a character buffer. The format typically includes the provided message and the system's error description for the given `error_code`. ```cpp void format_system_error(detail::buffer& out, int error_code, const char* message); ```