### Install fmtlib with vcpkg Source: https://github.com/fmtlib/fmt/blob/main/doc/get-started.md Install fmtlib using the vcpkg package manager. This involves cloning vcpkg, bootstrapping it, integrating it, and then installing fmt. ```bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install fmt ``` -------------------------------- ### Install fmtlib with Conan Source: https://github.com/fmtlib/fmt/blob/main/doc/get-started.md Install fmtlib using the Conan package manager. This command installs the latest version and builds missing dependencies. ```bash conan install -r conancenter --requires="fmt/[*]" --build=missing ``` -------------------------------- ### Core API Print Example Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md A simple example using the lightweight core API (`fmt/core.h`) for printing formatted output to the console. ```cpp #include fmt::print("The answer is {}.", 42); ``` -------------------------------- ### Install fmtlib on Debian/Ubuntu Source: https://github.com/fmtlib/fmt/blob/main/doc/get-started.md Install the fmtlib development package on Debian-based Linux distributions using apt. ```bash apt install libfmt-dev ``` -------------------------------- ### Install fmtlib on macOS with Homebrew Source: https://github.com/fmtlib/fmt/blob/main/doc/get-started.md Install fmtlib on macOS using the Homebrew package manager. ```bash brew install fmt ``` -------------------------------- ### Compile-time formatting example Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Illustrates compile-time formatting using `fmt::format_to` with `FMT_COMPILE`. This example converts an integer to a string at compile time. ```c++ #include consteval auto compile_time_itoa(int value) -> std::array { auto result = std::array(); fmt::format_to(result.data(), FMT_COMPILE("{}"), value); return result; } constexpr auto answer = compile_time_itoa(42); ``` -------------------------------- ### Install fmtlib with Conda Source: https://github.com/fmtlib/fmt/blob/main/doc/get-started.md Install fmtlib on Linux, macOS, and Windows using Conda from the conda-forge channel. ```bash conda install -c conda-forge fmt ``` -------------------------------- ### Alignment Examples Source: https://github.com/fmtlib/fmt/blob/main/doc/syntax.md Demonstrates left, right, and center alignment with optional fill characters for string formatting. Padding is added to meet the specified width. ```c++ fmt::format("[{:<10}]", "42"); // Result: "[42 ]" ``` ```c++ fmt::format("[{:>10}]", "42"); // Result: "[ 42]" ``` ```c++ fmt::format("[{:^10}]", "42"); // Result: "[ 42 ]" ``` ```c++ fmt::format("[{:*^10}]", "42"); // Result: "[****42****]" - '*' as fill ``` -------------------------------- ### Add Test Executable Example Source: https://github.com/fmtlib/fmt/blob/main/test/CMakeLists.txt Example of using the add_fmt_test function to create a test executable named 'args-test'. ```cmake add_fmt_test(args-test) ``` -------------------------------- ### Experimental fmt::writer API Example Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Demonstrates the experimental fmt::writer API for writing to different destinations like files or strings. Requires including . ```c++ #include void write_text(fmt::writer w) { w.print("The answer is {}.", 42); } int main() { // Write to FILE. write_text(stdout); // Write to fmt::ostream. auto f = fmt::output_file("myfile"); write_text(f); // Write to std::string. auto sb = fmt::string_buffer(); write_text(sb); std::string s = sb.str(); } ``` -------------------------------- ### Basic CMake Project Setup Source: https://github.com/fmtlib/fmt/blob/main/test/static-export-test/CMakeLists.txt Sets the minimum CMake version, project name, and basic build options like disabling shared libraries and controlling visibility. ```cmake cmake_minimum_required(VERSION 3.8...3.25) project(fmt-link CXX) set(BUILD_SHARED_LIBS OFF) set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) set(CMAKE_CXX_VISIBILITY_PRESET "hidden") ``` -------------------------------- ### Install cppformat on OS X with Homebrew Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Install the cppformat library on OS X using the Homebrew package manager. ```bash $ brew install cppformat ``` -------------------------------- ### Configure Installation Directory Source: https://github.com/fmtlib/fmt/blob/main/CMakeLists.txt Sets the installation directory for include files using 'set_verbose'. It uses CMAKE_INSTALL_INCLUDEDIR and allows it to be a cache string, relative or absolute path. ```cmake set_verbose( FMT_INC_DIR ${CMAKE_INSTALL_INCLUDEDIR} CACHE STRING "Installation directory for include files, a relative path that " "will be joined with ${CMAKE_INSTALL_PREFIX} or an absolute path.") ``` -------------------------------- ### Experimental std::filesystem::path Formatting Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Shows the experimental support for formatting `std::filesystem::path` objects. This example demonstrates printing a path to the console. ```c++ #include #include int main() { fmt::print("There is no place like {}.\n", std::filesystem::path("/home")); } ``` -------------------------------- ### Formatting with Text Styles and Colors in C++ Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Shows how to format strings with text styles and colors using fmtlib. This example applies bold emphasis and red foreground color to a formatted string. ```c++ #include std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), "The answer is {}.", 42); ``` -------------------------------- ### Find and Link Installed fmtlib with CMake Source: https://github.com/fmtlib/fmt/blob/main/doc/get-started.md Find and link an already installed version of fmtlib in your CMake project. This requires fmtlib to be installed on the system. ```cmake find_package(fmt) target_link_libraries( fmt::fmt) ``` -------------------------------- ### Basic Compile Test Source: https://github.com/fmtlib/fmt/blob/main/test/compile-error-test/CMakeLists.txt A minimal test case to ensure the basic compilation setup works correctly. ```cmake expect_compile(check "") ``` -------------------------------- ### Type Erasure Example Source: https://github.com/fmtlib/fmt/blob/main/doc/api.md Example demonstrating how to create custom formatting functions with compile-time checks and a small binary footprint using type erasure. ```APIDOC ## Type Erasure You can create your own formatting function with compile-time checks and small binary footprint, for example ([run](https://godbolt.org/z/b9Pbasvzc)): ```c++ #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); ``` Note that `vlog` is not parameterized on argument types which improves compile times and reduces binary code size compared to a fully parameterized version. ``` -------------------------------- ### Project Options Configuration Source: https://github.com/fmtlib/fmt/blob/main/CMakeLists.txt Defines various build options for the fmtlib project using the 'option' command. These control features like documentation, installation, testing, fuzzing, and more. ```cmake option(FMT_DOC "Generate the doc target." ${FMT_MASTER_PROJECT}) option(FMT_INSTALL "Generate the install target." ${FMT_MASTER_PROJECT}) option(FMT_TEST "Generate the test target." ${FMT_MASTER_PROJECT}) option(FMT_FUZZ "Generate the fuzz target." OFF) option(FMT_CUDA_TEST "Generate the cuda-test target." OFF) option(FMT_OS "Include OS-specific APIs." ON) option(FMT_MODULE "Build a module library." ${FMT_USE_CMAKE_MODULES}) option(FMT_SYSTEM_HEADERS "Expose headers with marking them as system." OFF) option(FMT_UNICODE "Enable Unicode support." ON) option(FMT_PEDANTIC "Enable extra warnings and expensive tests." OFF) option(FMT_WERROR "Halt the compilation with an error on compiler warnings." OFF) ``` -------------------------------- ### Applying Text Styles with fmt::styled Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Demonstrates how to apply text styles, such as bold or color, to individual arguments using `fmt::styled`. This example shows styling a timestamp and an error message. ```c++ #include #include int main() { auto now = std::chrono::system_clock::now(); fmt::print( "[{}] \{\}: \{\}\n", fmt::styled(now, fmt::emphasis::bold), fmt::styled("error", fg(fmt::color::red)), "something went wrong"); } ``` -------------------------------- ### Format Ranges and Containers Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Example of experimental support for formatting ranges, containers, and tuple-like types using `fmt/ranges.h`. This allows direct printing of collections. ```cpp #include std::vector v = {1, 2, 3}; fmt::print("{}", v); // prints {1, 2, 3} ``` -------------------------------- ### Output Iterator Support Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Example of using `fmt::format_to` with `std::back_inserter` to format data directly into a container like `std::vector`. ```cpp #include #include std::vector out; fmt::format_to(std::back_inserter(out), "{}", 42); ``` -------------------------------- ### Subsecond Formatting for Chrono Durations in C++ Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Demonstrates subsecond formatting for chrono durations using fmt/chrono.h. The example shows how to print milliseconds with fractional seconds. ```cpp #include int main() { fmt::print("{:%S}", std::chrono::milliseconds(1234)); } ``` -------------------------------- ### Add Test Executable with Extra Source Source: https://github.com/fmtlib/fmt/blob/main/test/CMakeLists.txt Example of using add_fmt_test to create a test executable with an additional source file. ```cmake add_fmt_test(format-test mock-allocator.h) ``` -------------------------------- ### Install cppformat on Debian Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Use this command to install the cppformat development package on Debian GNU/Linux and derived distributions. ```bash $ sudo apt-get install libcppformat1-dev ``` -------------------------------- ### Formatting Standard Containers Source: https://github.com/fmtlib/fmt/blob/main/doc/index.md fmtlib supports out-of-the-box formatting for standard types, including containers like std::vector. This example shows how to print a vector directly. ```cpp fmt::print("{}", std::vector{1, 2, 3}); ``` -------------------------------- ### Sign Formatting Examples Source: https://github.com/fmtlib/fmt/blob/main/doc/syntax.md Illustrates how to control the display of signs for numeric types. Options include always showing the sign, showing it only for negative numbers, or using a space for nonnegative numbers. ```c++ fmt::format("{:+d} {:+d}", 7, -7); // Result: "+7 -7" ``` ```c++ fmt::format("{: d} {: d}", 7, -7); // Result: " 7 -7" ``` -------------------------------- ### Unicode String Formatting Source: https://github.com/fmtlib/fmt/blob/main/doc/index.md This example shows fmtlib's portable Unicode support, ensuring correct printing of non-ASCII characters across different operating systems. ```cpp fmt::print("Слава Україні!"); ``` -------------------------------- ### Format String Compilation with Empty String Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Example of using fmt::format with FMT_COMPILE for an empty format string. This addresses a fix for handling empty format strings during compilation. ```cpp auto s = fmt::format(FMT_COMPILE("")); ``` -------------------------------- ### Dynamic Width in Chrono Formatting in C++ Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Demonstrates handling dynamic width in chrono formatting. The example formats seconds into HH:MM:SS format with a specified width, padding with spaces. ```c++ auto s = fmt::format("{0:{1}%H:%M:%S}", std::chrono::seconds(12345), 12); // ^ width argument index ^ width // s == "03:25:45 " ``` -------------------------------- ### Format Chrono Subseconds Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Implements formatting for subseconds within chrono durations. This example shows formatting microseconds. ```cpp #include int main() { // prints 01.234567 fmt::print("{:%S} ", std::chrono::microseconds(1234567)); } ``` -------------------------------- ### Compile-Time Floating Point Formatting Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Demonstrates compile-time floating-point formatting using FMT_COMPILE. This example shows how to format a double value at compile time, requiring no header-only mode. ```c++ #include #include consteval auto compile_time_dtoa(double value) -> std::array { auto result = std::array(); fmt::format_to(result.data(), FMT_COMPILE("{}"), value); return result; } constexpr auto answer = compile_time_dtoa(0.42); ``` -------------------------------- ### Experimental std::variant Formatting Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Demonstrates the experimental support for formatting `std::variant` types. This example shows how a `std::variant` containing an integer is printed. ```c++ #include #include int main() { auto v = std::variant(42); fmt::print("{}\n", v); } ``` -------------------------------- ### Format vector elements with fmt::join Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Utilize `fmt::join()` from `fmt/format.h` to format elements of a range, separated by a specified string. This example demonstrates formatting a vector of doubles. ```c++ #include "fmt/format.h" std::vector v = {1.2, 3.4, 5.6}; // Prints "(+01.20, +03.40, +05.60)". fmt::print("({:+06.2f})", fmt::join(v.begin(), v.end(), ", ")); ``` -------------------------------- ### UTF-8 Handling and Unicode Output in C++ Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Demonstrates improved UTF-8 handling for displaying Unicode characters correctly. This example shows how to format strings with alignment and borders, producing a visually appealing output on systems supporting Unicode. ```c++ fmt::print("┌{0:─^{2}}┐\n""│{1: ^{2}}│\n""└{0:─^{2}}┘\n", "", "Прывітанне, свет!", 21); ``` -------------------------------- ### Custom formatter for struct point with nested_formatter Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Example of creating a custom formatter for a struct using fmt::nested_formatter. This allows applying formatters to subobjects. ```c++ #include struct point { double x, y; }; template <> struct fmt::formatter : nested_formatter { auto format(point p, format_context& ctx) const { return write_padded(ctx, [=](auto out) { return format_to(out, "({}, {})", nested(p.x), nested(p.y)); }); } }; int main() { fmt::print("[{:>20.2f}]", point{1, 2}); } ``` -------------------------------- ### fmt::format_to Safety Improvement Example Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Demonstrates the improved safety of fmt::format_to when writing to a small buffer. The output is now truncated instead of causing a buffer overflow. ```c++ auto volkswagen = char[4]; auto result = fmt::format_to(volkswagen, "elephant"); ``` -------------------------------- ### Format Time Points with Fill, Align, and Width Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md The time point formatter now supports fill, alignment, and width specifiers. This example demonstrates right alignment with a width of 8. ```cpp #include int main() { // prints " 2023" fmt::print("{:>8%Y} ", std::chrono::system_clock::now()); } ``` -------------------------------- ### Improved Width Computation for Text Alignment Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Illustrates improved width computation for text alignment, particularly with multi-byte characters. The example shows left alignment with padding. ```cpp #include int main() { fmt::print("{:-<10}{}\n", "你好", "世界"); fmt::print("{:-<10}{}\n", "hello", "world"); } ``` -------------------------------- ### Clone and Build format-benchmark Repository Source: https://github.com/fmtlib/fmt/blob/main/README.md Clone the format-benchmark repository and its submodules, then configure it using CMake to prepare for running benchmarks. ```bash git clone --recursive https://github.com/fmtlib/format-benchmark.git cd format-benchmark cmake . ``` -------------------------------- ### Compile-time format string check example Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Demonstrates how compile-time format string checks catch invalid format specifiers for string types. This requires C++20 consteval support. ```c++ #include int main() { fmt::print("{:d}", "I am not a number"); } ``` -------------------------------- ### std::thread::id Formatting Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Provides an example of formatting `std::thread::id` using the formatter specialization available in `fmt/std.h`. This is a convenient way to display the current thread's identifier. ```c++ #include #include int main() { fmt::print("Current thread id: \{\}\n", std::this_thread::get_id()); } ``` -------------------------------- ### Compile-Time Format String Checks with Named Arguments in C++ Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Illustrates compile-time format string checks using UDL-based named arguments. This example checks for valid format specifiers for integer types at compile time, requiring C++20 consteval and non-type template parameter support. ```cpp #include int main() { using namespace fmt::literals; fmt::print("{answer:s}", "answer"_a=42); } ``` -------------------------------- ### Format Time Points Before Epoch Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Handles formatting of time points that occur before the epoch, ensuring correct output for negative time values. This example prints seconds for a time point 250 milliseconds before the epoch. ```cpp #include int main() { auto t = std::chrono::system_clock::from_time_t(0) - std::chrono::milliseconds(250); fmt::print("{:%S} ", t); // prints 59.750000000 } ``` -------------------------------- ### Compile-time error for missing timezone info with fmt::print Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md This example shows how fmtlib provides compile-time diagnostics when timezone information is unavailable for formatting. It uses the 'Z' specifier with std::chrono::local_seconds. ```c++ fmt::print("{:Z}", std::chrono::local_seconds()); ``` -------------------------------- ### Build fmtlib from Source with CMake Source: https://github.com/fmtlib/fmt/blob/main/doc/get-started.md Standard CMake workflow to build fmtlib from source. This involves creating a build directory, configuring with CMake, and then building. ```bash mkdir build cd build cmake .. make ``` -------------------------------- ### Escaping String Range Elements in C++ Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Demonstrates how fmt/ranges.h now escapes string range elements, preventing issues with newlines within strings. The example shows the difference in output for a vector containing a string with a newline character. ```cpp #include #include int main() { fmt::print("{}", std::vector{"\naan"}); } ``` -------------------------------- ### Locale-Independent vs. Localized Chrono Specifiers Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Illustrates the difference between locale-independent chrono specifiers (default) and localized formatting using the `'L'` specifier. For example, a weekday formatted in Russian locale prints "пн" with `{:L}`. ```cpp #include int main() { std::locale::global(std::locale("ru_RU.UTF-8")); auto monday = std::chrono::weekday(1); fmt::print("{}\n", monday); // prints "Mon" fmt::print("{:L}\n", monday); // prints "пн" } ``` -------------------------------- ### Build fmtlib Documentation with CMake Source: https://github.com/fmtlib/fmt/blob/main/doc/get-started.md Build the documentation for fmtlib after generating CMake build scripts. Requires Python, Doxygen, and MkDocs with specific plugins. ```bash make doc ``` -------------------------------- ### Formatting std::byte with fmt::join Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Demonstrates using `fmt::join` with `std::byte` and other formattable types. The output for the example vector `{std::byte(4), std::byte(2)}` joined by an empty string is "42". ```cpp #include #include #include int main() { auto bytes = std::vector{std::byte(4), std::byte(2)}; fmt::print("{}", fmt::join(bytes, "")); } ``` -------------------------------- ### fmt::join with Initializer List in C++ Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Shows how fmt::join can now accept an initializer_list, simplifying the process of joining elements from a list into a formatted string. ```c++ fmt::join(initializer_list, separator); ``` -------------------------------- ### Integer Formatting with fmtlib Source: https://github.com/fmtlib/fmt/blob/main/doc/syntax.md Demonstrates various integer formatting options including decimal, hexadecimal, octal, and binary bases, with and without prefixes. Use for controlling integer output representation. ```c++ fmt::format("{:d} {:#x} {:#o} {:#b}", 42, 42, 42, 42); // Result: "42 0x2a 052 0b101010" ``` ```c++ fmt::format("{:#06x}", 0xfe); // # adds the prefix, 06 zero-pads to width 6 // Result: "0x00fe" ``` -------------------------------- ### Improved Error Reporting for Unformattable Types Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Shows an example of an unformattable type and the improved error message that now directly includes the type name. ```c++ #include struct how_about_no {}; int main() { fmt::print("{}", how_about_no()); } ``` -------------------------------- ### Run Speed Test Benchmark Source: https://github.com/fmtlib/fmt/blob/main/README.md Execute the speed test benchmark after cloning and building the format-benchmark repository. ```bash make speed-test ``` -------------------------------- ### Enable Header-Only Configuration Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Shows how to configure the fmt library for header-only usage by defining `FMT_HEADER_ONLY` before including the main header file. ```c++ #define FMT_HEADER_ONLY #include "format.h" ``` -------------------------------- ### Make Format Args for Variadic Reporting Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Shows how to use `fmt::make_format_args` to capture formatting arguments, enabling functions like `vprint` to handle them. This is useful for implementing custom reporting or logging functions. ```cpp // Prints formatted error message. void vreport_error(const char *format, fmt::format_args args) { fmt::print("Error: "); fmt::vprint(format, args); } template void report_error(const char *format, const Args & ... args) { vreport_error(format, fmt::make_format_args(args...)); } ``` -------------------------------- ### Find and Link fmt Package in CMake Source: https://github.com/fmtlib/fmt/blob/main/test/find-package-test/CMakeLists.txt Use this snippet to find the fmt package and link it to your executable. Ensure the fmt package is installed and discoverable by CMake. ```cmake cmake_minimum_required(VERSION 3.8...3.25) project(fmt-test) find_package(FMT REQUIRED) add_executable(library-test main.cc) target_link_libraries(library-test fmt::fmt) target_compile_options(library-test PRIVATE ${PEDANTIC_COMPILE_FLAGS}) target_include_directories(library-test PUBLIC SYSTEM .) ``` -------------------------------- ### Print to stdout with fmtlib Source: https://github.com/fmtlib/fmt/blob/main/README.md Use `fmt::print` for simple output to the standard output stream. Requires including ``. ```c++ #include int main() { fmt::print("Hello, world!\n"); } ``` -------------------------------- ### Precision for Floating-Point Durations in C++ Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Shows how to format floating-point durations with specified precision using fmtlib. The example formats a std::chrono::duration. ```c++ auto s = fmt::format("{:.1}", std::chrono::duration(1.234)); // s == 1.2s ``` -------------------------------- ### Format std::experimental::string_view Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Print `std::experimental::string_view` using fmt::print. Requires including `` and ``. ```cpp #include #include fmt::print("{}", std::experimental::string_view("foo")); ``` -------------------------------- ### fmt::print Performance Benchmark Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Compares the performance of printf, fmt::print (10.x), and fmt::print (11.0) in a benchmark. Version 11.0 shows significant improvement. ```text ------------------------------------------------------- Benchmark Time CPU Iterations ------------------------------------------------------- printf 81.8 ns 81.5 ns 8496899 fmt::print (10.x) 63.8 ns 61.9 ns 11524151 fmt::print (11.0) 51.3 ns 51.0 ns 13846580 ``` -------------------------------- ### Format Wide String with Date Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Illustrates fixing the formatting of types with overloaded `operator<<` for `std::wostream`. This example shows formatting a date object into a wide string. ```c++ fmt::format(L"The date is {0}", Date(2012, 12, 9)); ``` -------------------------------- ### Formatter Specialization for User-Defined Types Source: https://github.com/fmtlib/fmt/blob/main/doc/api.md Specialize fmt::formatter for a user-defined type to control its string representation. This example shows formatting a type 'A' by delegating to the string formatter. ```c++ fmt::formatter { auto format(const A& a, format_context& ctx) const { return formatter::format(a.name(), ctx); } }; ``` -------------------------------- ### Configure Meson for static fmt build Source: https://github.com/fmtlib/fmt/blob/main/doc/get-started.md To build fmt as a static library with Meson, specify 'default_library=static' when defining the subproject. ```meson fmt = subproject('fmt', default_options: 'default_library=static') mt_dep = fmt.get_variable('fmt_dep') ``` -------------------------------- ### Format std::bitset Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Illustrates formatting std::bitset using fmt/std.h. Ensure the correct header is included. ```c++ #include #include int main() { fmt::print("{} ", std::bitset<6>(42)); // prints "101010" } ``` -------------------------------- ### Basic Positional Formatting Source: https://github.com/fmtlib/fmt/blob/main/doc/syntax.md Demonstrates basic string formatting using positional arguments. Arguments are substituted in the order they appear. ```c++ fmt::format("hello, {}", "world"); // Result: "hello, world" ``` -------------------------------- ### FetchContent for fmtlib with CMake Source: https://github.com/fmtlib/fmt/blob/main/doc/get-started.md Use FetchContent to automatically download and include fmtlib as a dependency at CMake configure time. Ensure you have 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) ``` -------------------------------- ### Build fmt-c Static Library Source: https://github.com/fmtlib/fmt/blob/main/CMakeLists.txt Builds a static library named `fmt-c` from `src/fmt-c.cc`. It requires C++11 and sets the MSVC preprocessor option if applicable. It also links against the main `fmt::fmt` library and defines an alias. ```cmake add_library(fmt-c STATIC src/fmt-c.cc) target_compile_features(fmt-c INTERFACE c_std_11) if (MSVC) target_compile_options(fmt-c PUBLIC /Zc:preprocessor) endif () target_link_libraries(fmt-c PUBLIC fmt::fmt) add_library(fmt::fmt-c ALIAS fmt-c) ``` -------------------------------- ### Formatter with Nested Formatting Support Source: https://github.com/fmtlib/fmt/blob/main/doc/api.md Use `nested_formatter` to apply a formatter to subobjects within a user-defined type. This example formats a `point` struct by formatting its `x` and `y` members as doubles. ```cpp #include struct point { double x, y; }; template <> struct fmt::formatter : nested_formatter { auto format(point p, format_context& ctx) { return write_padded(ctx, [=](auto out) { return format_to(out, "({}, {})", this->nested(p.x), this->nested(p.y)); }); } }; int main() { fmt::print("[{:>20.2f}]", point{1, 2}); } ``` -------------------------------- ### Compile-time Formatting Error Detection Source: https://github.com/fmtlib/fmt/blob/main/doc/index.md This example demonstrates how fmtlib catches formatting errors at compile time. Ensure the format specifier matches the argument type to avoid errors. ```cpp fmt::format("{:d}", "I am not a number"); ``` -------------------------------- ### Named Argument Formatting Source: https://github.com/fmtlib/fmt/blob/main/doc/syntax.md Illustrates formatting using named arguments. This requires passing arguments using `fmt::arg` and referencing them by name in the format string. ```c++ fmt::format("{greeting}, {name}!", fmt::arg("greeting", "hi"), fmt::arg("name", "fmt")); // Result: "hi, fmt!" ``` -------------------------------- ### Format string with fmtlib Source: https://github.com/fmtlib/fmt/blob/main/README.md Use `fmt::format` to create formatted strings. The placeholder `{}` is replaced by the argument. ```c++ std::string s = fmt::format("The answer is {}.", 42); // s == "The answer is 42." ``` -------------------------------- ### Printf-like Formatting with fmt/printf.h Source: https://github.com/fmtlib/fmt/blob/main/doc/api.md Provides type-safe `printf`-style formatting. Throws an exception on type mismatches. Supports POSIX extension for positional arguments. Include `fmt/printf.h`. ```cpp #include #include int main() { // Example using printf fmt::printf("%s %d\n", "Hello", 123); // Example using fprintf fmt::fprintf(stdout, "%s %d\n", "Hello", 123); // Example using sprintf char buffer[50]; fmt::sprintf(buffer, "%s %d\n", "Hello", 123); printf("sprintf output: %s", buffer); return 0; } ``` -------------------------------- ### Compile-time Format String Checks Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Compile-time checks are added to the format_to overload that takes fmt::memory_buffer. This example shows an invalid type specifier that would cause a compile-time error. ```c++ fmt::memory_buffer buf; // Compile-time error: invalid type specifier. fmt::format_to(buf, fmt("{:d}"), "foo"); ``` -------------------------------- ### Import fmt target in build2 buildfile Source: https://github.com/fmtlib/fmt/blob/main/doc/get-started.md Import the fmt library target and use it as a prerequisite for your own target in your build2 'buildfile'. ```build2 import fmt = fmt%lib{fmt} lib{mylib} : cxx{**} ... $fmt ``` -------------------------------- ### Sentinel Support for fmt::join in C++ Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Adds sentinel support to `fmt::join`, allowing custom delimiters for ranges that define their own sentinel. This example shows how to use a `zstring` with a `zstring_sentinel`. ```c++ struct zstring_sentinel {}; bool operator==(const char* p, zstring_sentinel) { return *p == '\0'; } bool operator!=(const char* p, zstring_sentinel) { return *p != '\0'; } struct zstring { const char* p; const char* begin() const { return p; } zstring_sentinel end() const { return {}; } }; auto s = fmt::format("{}", fmt::join(zstring{"hello"}, "_")); // s == "h_e_l_l_o" ``` -------------------------------- ### Basic Usage of fmt::print with User-Defined Types Source: https://github.com/fmtlib/fmt/blob/main/doc/api.md Demonstrates how to print a user-defined type using fmt::print after providing a formatter specialization. Ensure the necessary headers are included. ```c++ // demo.cc: #include "demo.h" #include int main() { B b; A& a = b; fmt::print("{}", a); // Output: B } ``` -------------------------------- ### Format std::stack Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Shows how to format standard container adapters like std::stack using fmt/ranges.h. This allows for easy printing of container contents. ```c++ #include #include #include int main() { auto s = std::stack>(); for (auto b: {true, false, true}) s.push(b); fmt::print("{}\n", s); // prints [true, false, true] } ``` -------------------------------- ### Custom Formatter with Compile-time Error Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Shows how to implement a custom formatter for a type. This example defines a formatter for 'Answer' that throws a compile-time error for invalid specifiers, leveraging the extension API for compile-time processing. ```cpp struct Answer {}; namespace fmt { template <> struct formatter { constexpr auto parse(parse_context& ctx) { auto it = ctx.begin(); spec = *it; if (spec != 'd' && spec != 's') throw format_error("invalid specifier"); return ++it; } template auto format(Answer, FormatContext& ctx) { return spec == 's' ? format_to(ctx.begin(), "{}", "fourty-two") : format_to(ctx.begin(), "{}", 42); } char spec = 0; }; } std::string s = format(fmt("{:x}"), Answer()); ``` -------------------------------- ### Format User-Defined Enum with format_as Source: https://github.com/fmtlib/fmt/blob/main/doc/api.md Use `format_as` to make a user-defined type formattable as another type. Define `format_as` in the same namespace as the type. This example shows formatting an enum class by returning its underlying value. ```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 } ``` -------------------------------- ### Run Bloat Test Benchmark Source: https://github.com/fmtlib/fmt/blob/main/README.md Execute the bloat test benchmark, which assesses compile time and executable size, after cloning and building the format-benchmark repository. ```bash make bloat-test ``` -------------------------------- ### Formatting Floating-Point Values as Percentages in C++ Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Demonstrates the experimental '%' format specifier for formatting floating-point values as percentages. The precision can be controlled. ```c++ auto s = fmt::format("{:.1%}", 0.42); // s == "42.0%" ``` -------------------------------- ### Dynamic Argument Storage and Formatting in C++ Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Illustrates the use of experimental dynamic argument storage for formatting. This allows for a flexible way to pass arguments to formatting functions, especially when the number or types of arguments are not known at compile time. ```c++ fmt::dynamic_format_arg_store store; store.push_back("answer"); store.push_back(42); fmt::vprint("The {} is {}.\n", store); ``` -------------------------------- ### Generic Formatter for Base Class Hierarchy Source: https://github.com/fmtlib/fmt/blob/main/doc/api.md Define a template specialization of `fmt::formatter` to handle a hierarchy of classes. This example uses `std::enable_if_t` and `std::is_base_of_v` to create a formatter for types derived from a base class `A`. ```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>> : ``` -------------------------------- ### Specialize fmt::formatter for a User-Defined Enum Source: https://github.com/fmtlib/fmt/blob/main/doc/api.md Specialize `fmt::formatter` for a user-defined type to gain full control over parsing and formatting. This example specializes `formatter` for `color` by inheriting from `formatter` and implementing the `format` method. ```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); } ``` -------------------------------- ### Date and Time Formatting with fmt/time.h Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Use fmt/time.h for strftime-like date and time formatting. This requires including the header and using std::time and std::localtime. ```c++ #include "fmt/time.h" std::time_t t = std::time(nullptr); // Prints "The date is 2016-04-29." (with the current date) fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t)); ``` -------------------------------- ### Compile-time Format String Check Example Source: https://github.com/fmtlib/fmt/blob/main/doc/ChangeLog-old.md Demonstrates compile-time format string validation. An invalid specifier for a string type will result in a compile-time error. Requires C++14 for relaxed constexpr support; otherwise, checks occur at runtime. ```cpp #include std::string s = format(fmt("{:d}"), "foo"); ``` -------------------------------- ### Print with colors and text styles Source: https://github.com/fmtlib/fmt/blob/main/README.md Apply colors and text styles (bold, underline, italic) to output using `fmt::print` with style modifiers. Requires including ``. ```c++ #include int main() { fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, "Hello, {}!\n", "world"); fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | fmt::emphasis::underline, "Olá, {}!\n", "Mundo"); fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, "你好{}!\n", "世界"); } ``` -------------------------------- ### Format std::filesystem::path with generic representation Source: https://github.com/fmtlib/fmt/blob/main/ChangeLog.md Demonstrates formatting std::filesystem::path using the generic representation ('g') with fmt/std.h. Note the platform-specific output. ```c++ #include #include int main() { fmt::print("{:g} ", std::filesystem::path("C:\\foo")); } ```