353bd895a Add FMT_EXPORT on ranges.h customization points (#4476) 953cffa70 Replace memset with constexpr fill_n in bigint::align (#4471) 571c02d47 Add xchar support for std::byte formatter (#4480) f4345467f Fix compilation on clang-21 / libc++-21 (#4477) 1ef834807 Properly constrain `detail::copy` optimization (#4474) a5dccffa5 Add double and float support to scan test 4a149f513 Test non-SSO constexpr string formatting 067bc479b Avoid redundant work when processing UTF-8 strings (#4475) 730fd4d9a Remove redundant tests 5860688d7 Enable constexpr support for fmt::format (fmtlib#3403) (#4456) 46be88bc1 Cleanup FP formatting cc8891490 Export fmt::dynamic_format_arg_store in fmt module (#4459) fc0c76a07 Handle large precision 6332a3852 Bump ossf/scorecard-action from 2.4.0 to 2.4.2 (#4462) 02de29e00 Remove a reference to a compromised account 6d51c78c1 Cleanup FP formatting 0f4e9d0bd Cleanup FP formatting d9d50495a Optimize the default FP formatting befbc5fdb Fix ADL lookup for memory_buffer 8aa1d6a9f Minor cleanup 6d79757a3 Interpret precision as display width (#4443) 1ff0b7f5e Cleanup warning suppression ea985e84f Remove some implicit conversions (#4447) f7033da09 Avoid include locale inline if C++20 modules are enabled (#4451) b723c021d Give useful error when misusing fmt::ptr. (#4453) 3ba3c390f Clarify that formatting of pointers is disallowed ab161a71c Fix some typos in comments (#4448) b5266fd3b Remove some redundant `const`s (#4445) 9b0ebd443 Cleanup base-test 7af94e559 Remove old gcc workaround 2924fcf8f Cleanup base-test 102752ad4 Update docs a6cd72c9e Cleanup base-test 07885271a Minor cleanup 4999416e5 Fix reference_wrapper ambiguity with format_as (#4434) 55a8f6a4b Change component prefix for NSIS compatibility (#4442) eb9a95d42 Clarify that formatting of pointers is disallowed d5c33e4f4 Make template parameter order consistent a2225f288 Remove unused include b43b2f953 Cleanup standard formatters 1312b4a16 Cleanup standard formatters 4404dc05d Consolidate implementation details 7bb6fcb32 Bump version 59259a5fd Make a doc directory if it doesn't exist 542ea7c40 Clarify that Formatter parameter is deprecated 40626af88 Update version 7fdd6846b Bump version 6caff7ed9 Cleanup test 71a548387 Update changelog 448929d49 Update and apply clang-format 26d87edab Bump github/codeql-action from 3.28.13 to 3.28.16 (#4432) 505ee058f Update changelog ccab41719 Update changelog ec1349d34 Update changelog 0ed2a65a8 Clarify why we use __builtin_strlen instead of strlen e22c94307 Update changelog b252bad3c Update changelog 268083123 Cleanun string_view 8978ab09b Avoiding __builtin_strlen (#4429) c936e2e44 Implement debug format for error_code a7d7b894c Implement the s specifier for error_code e98155a6f Remove redundant specializations 41b3bed4d Clarify why we don't use qualified names 67d9e4932 Update changelog 9db5e4df2 Don't specialize std::is_floating_point 906eaf2dd Make specifier order consistent 9f6c12c3d Remove deprecated localtime from docs 2d0518b5f Fix cmake error in pedantic mode (#4426) c81cbed2b Simplify test c7925241c Remove `core.h` from README (#4422) c70913835 Add support for incomplete types db405954c Remove `fmt/core.h` from docs (#4421) 0a917ee2f Minor comment tweak 969d4aef6 Update doc image 8061c7c8c Cleanup duration formatter 7b59df411 Remove redundant member b8192d233 Fix build error with MSVC v141 (#4413) e814b5fab Reduce template parametrization ed0d216f7 Fix localization and formatting of timezone names bd9554a29 Fix formatting of timezone names f086dc0d2 Fix timezone handling in tm f10b6dd81 Improve chrono formatting f470b9c56 Cleanup chrono tests and set consistent TZ b28214487 Fix handling of %Z 6d69f0c5f Improve chorno tests da776c9a6 Test timezone 64db979e3 Added a missing FMT_STRING in fmt::println() (#4407) 5f2e61fdd Cleanup chrono detail b3d45e1d3 Remove fmt_detail 5f6fb96df Bump github/codeql-action from 3.28.8 to 3.28.13 (#4403) 5199e0f88 Fix a flush issue on libstdc++ 2f5843057 Move buffering tests to os-test d5d32c1e8 Bazel support: Update platforms to 0.0.11 (#4400) 204661287 Improve local_time test e1ab38336 Report an error when timezone is not available b9e0e94a0 Enable more chrono tests on Windows a81842428 Update changelog f53055efe Revert "Workaround an ABI issue in spdlog" b2dfcb2b8 Fix local_time test 7ac97cbd1 Enable some local_time tests and make them deterministic 17898794a Use fmt::local_time 443a8ef34 Deprecate fmt::localtime 3607e92dc Bump version 43e31614c Test ambiguous time 989826ce5 Update changelog 9d6e24c64 Fix handling of long with FMT_BUILTIN_TYPES=0 0843317e0 Update changelog 784eac839 Workaround an ABI issue in spdlog 6fdf225a3 Always inline value ctors in optimized gcc mode only 332da79bf Always inline value ctors 7b273fbb5 Minor cleanup 191c504b1 Cleanup build config d13fb6092 Cleanup build config dd780fde4 Add clang-3.4 37e647471 Fix dynamic named arg format spec handling (#4361) 77c0fc07d Switch to supported ubuntu image 9212ff6ca Apply coding conventions and use constexpr 864bdf963 Report error on duplicate named arg names (#4367) b776cf66f Optimize `text_style` using bit packing (#4363) bdbf957b9 Bump msys2/setup-msys2 from 2.25.0 to 2.27.0 577fd3be8 Fix TU-local entity exposition error in GCC 15 faac8b1fa Remove exports in std.h 123913715 Update version 8c1059b92 Update changelog 4e5aafbf4 Bump version db30fb3b8 Update changelog 3401ce2be Fix ABI compatibility 7f7695524 Fix conflict with std::ignore (#4356) 251320fcb Add .vs folder to .gitignore (#4355) 94ab51cb8 Simplify implementation of `operator""_cf` (#4349) 0ca42e836 Workaround an MSVC v140 bug ed27df576 Replace forward slashes by backslashes in BMI path for MSVC. (#4344) d42a068db Apply coding conventions f2cec917d Move is_compiled_string to public API (#4342) d5b866e24 fix gcc 8.3 compile errors (#4336) 5676e408f Bump github/codeql-action from 3.27.0 to 3.28.8 (#4337) 71d24b564 Bump actions/upload-artifact from 4.4.0 to 4.6.0 (#4339) c9267da4d Fix typo in `FMT_HAS_BUILTIN` check 373855c1b Clarify difference in FP representation 52eeeb52a Make exponent threshold depend on representation (#3649) 9cf9f38ed Update version 4946bdb72 Update changelog 01a5b56f0 Fix error of unitialized variable FMT_HEADERS cb6fdf219 Restore constraint on map formatter (#4326) f841ae61e Fix #4303: avoid instantiating formatter<const T> (#4325) a3d05d70c Silence a constexpr warning when compiling with MSVC and /W4 (#4322) 41539c29f Workaround a bug in gcc 6 (#4318) aabe63910 Tweak changelog f90090be2 Update changelog 9ff9c695d Bump version 06ad1224e Update changelog 5f0572acd Workaround a compilation error on gcc 9.4 898d43857 Fix formatting into std::ostreambuf_iterator using a compiled format (#4312) 937b7c5c1 Add args() accessor back to fmt::format_context (#4310) 01914f038 Reduce size of basic_specs c43da3570 Workaround an ICE when using modules with gcc 14.2 and earlier 8303d140a Update version b0b3dc5ff Bump version 586ea06f0 Rename set_fill to copy_fill_from 5750f434f Update changelog bfbdc2be9 Add parameter to the fallback to_sys function. 87e007267 Update changelog d57040f94 Prefix components 21aa0956d Restore ABI compatibility 3f864a450 Address MSVC C4127 warning when formatting non unicode `tm` (#4299) git-subtree-dir: external/fmt git-subtree-split: 353bd895a2bf9d0b1bc5977dc002fb6e0cdb0960
20 KiB
API Reference
The {fmt} library API consists of the following components:
fmt/base.h: the base API providing main formatting functions forchar/UTF-8 with C++20 compile-time checks and minimal dependenciesfmt/format.h:fmt::formatand other formatting functions as well as locale supportfmt/ranges.h: formatting of ranges and tuplesfmt/chrono.h: date and time formattingfmt/std.h: formatters for standard library typesfmt/compile.h: format string compilationfmt/color.h: terminal colors and text stylesfmt/os.h: system APIsfmt/ostream.h:std::ostreamsupportfmt/args.h: dynamic argument listsfmt/printf.h: safeprintffmt/xchar.h: optionalwchar_tsupport
All functions and types provided by the library reside in namespace fmt
and macros have prefix FMT_.
Base API
fmt/base.h defines the base API which provides main formatting functions
for char/UTF-8 with C++20 compile-time checks. It has minimal include
dependencies for better compile times. This header is only beneficial when
using {fmt} as a library (the default) and not in the header-only mode.
It also provides formatter specializations for the following types:
int,long long,unsigned,unsigned long longfloat,double,long doubleboolcharconst char*,fmt::string_viewconst void*
The following functions use format string syntax similar to that of str.format in Python. They take fmt and args as arguments.
fmt is a format string that contains literal text and replacement fields
surrounded by braces {}. The fields are replaced with formatted arguments
in the resulting string. fmt::format_string is a format
string which can be implicitly constructed from a string literal or a
constexpr string and is checked at compile time in C++20. To pass a runtime
format string wrap it in fmt::runtime.
args is an argument list representing objects to be formatted.
I/O errors are reported as std::system_error exceptions unless
specified otherwise.
::: print(format_string<T...>, T&&...)
::: print(FILE*, format_string<T...>, T&&...)
::: println(format_string<T...>, T&&...)
::: println(FILE*, format_string<T...>, T&&...)
::: format_to(OutputIt&&, format_string<T...>, T&&...)
::: format_to_n(OutputIt, size_t, format_string<T...>, T&&...)
::: format_to_n_result
::: formatted_size(format_string<T...>, T&&...)
Formatting User-Defined Types
The {fmt} library provides formatters for many standard C++ types.
See fmt/ranges.h for ranges and tuples including standard
containers such as std::vector, fmt/chrono.h for date and
time formatting and fmt/std.h for other standard library types.
There are two ways to make a user-defined type formattable: providing a
format_as function or specializing the formatter struct template.
Formatting of non-void pointer types is intentionally disallowed and they
cannot be made formattable via either extension API.
Use format_as if you want to make your type formattable as some other
type with the same format specifiers. The format_as function should
take an object of your type and return an object of a formattable type.
It should be defined in the same namespace as your type.
Example (run):
#include <fmt/format.h>
namespace kevin_namespacy {
enum class film {
house_of_cards, american_beauty, se7en = 7
};
auto format_as(film f) { return fmt::underlying(f); }
}
int main() {
fmt::print("{}\n", kevin_namespacy::film::se7en); // Output: 7
}
Using specialization is more complex but gives you full control over
parsing and formatting. To use this method specialize the formatter
struct template for your type and implement parse and format
methods.
The recommended way of defining a formatter is by reusing an existing one via inheritance or composition. This way you can support standard format specifiers without implementing them yourself. For example:
// color.h:
#include <fmt/base.h>
enum class color {red, green, blue};
template <> struct fmt::formatter<color>: formatter<string_view> {
// parse is inherited from formatter<string_view>.
auto format(color c, format_context& ctx) const
-> format_context::iterator;
};
// color.cc:
#include "color.h"
#include <fmt/format.h>
auto fmt::formatter<color>::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<string_view>::format(name, ctx);
}
Note that formatter<string_view>::format is defined in fmt/format.h
so it has to be included in the source file. Since parse is inherited
from formatter<string_view> it will recognize all string format
specifications, for example
fmt::format("{:>10}", color::blue)
will return " blue".
In general the formatter has the following form:
template <> struct fmt::formatter<T> {
// Parses format specifiers and stores them in the formatter.
//
// [ctx.begin(), ctx.end()) is a, possibly empty, character range that
// contains a part of the format string starting from the format
// specifications to be parsed, e.g. in
//
// fmt::format("{:f} continued", ...);
//
// the range will contain "f} continued". The formatter should parse
// specifiers until '}' or the end of the range. In this example the
// formatter should parse the 'f' specifier and return an iterator
// pointing to '}'.
constexpr auto parse(format_parse_context& ctx)
-> format_parse_context::iterator;
// Formats value using the parsed format specification stored in this
// formatter and writes the output to ctx.out().
auto format(const T& value, format_context& ctx) const
-> format_context::iterator;
};
It is recommended to at least support fill, align and width that apply to the whole object and have the same semantics as in standard formatters.
You can also write a formatter for a hierarchy of classes:
// demo.h:
#include <type_traits>
#include <fmt/format.h>
struct A {
virtual ~A() {}
virtual std::string name() const { return "A"; }
};
struct B : A {
virtual std::string name() const { return "B"; }
};
template <typename T>
struct fmt::formatter<T, std::enable_if_t<std::is_base_of_v<A, T>, char>> :
fmt::formatter<std::string> {
auto format(const A& a, format_context& ctx) const {
return formatter<std::string>::format(a.name(), ctx);
}
};
// demo.cc:
#include "demo.h"
#include <fmt/format.h>
int main() {
B b;
A& a = b;
fmt::print("{}", a); // Output: B
}
Providing both a formatter specialization and a format_as overload is
disallowed.
::: basic_format_parse_context
::: context
::: format_context
Compile-Time Checks
Compile-time format string checks are enabled by default on compilers
that support C++20 consteval. On older compilers you can use the
FMT_STRING macro defined in fmt/format.h instead.
Unused arguments are allowed as in Python's str.format and ordinary functions.
See Type Erasure for an example of how to enable compile-time
checks in your own functions with fmt::format_string while avoiding template
bloat.
::: fstring
::: format_string
::: runtime(string_view)
Type Erasure
You can create your own formatting function with compile-time checks and small binary footprint, for example (run):
#include <fmt/format.h>
void vlog(const char* file, int line,
fmt::string_view fmt, fmt::format_args args) {
fmt::print("{}: {}: {}", file, line, fmt::vformat(fmt, args));
}
template <typename... T>
void log(const char* file, int line,
fmt::format_string<T...> 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.
::: make_format_args(T&...)
::: basic_format_args
::: format_args
::: basic_format_arg
Named Arguments
::: arg(const Char*, const T&)
Named arguments are not supported in compile-time checks at the moment.
Compatibility
::: basic_string_view
::: string_view
Format API
fmt/format.h defines the full format API providing additional
formatting functions and locale support.
::: format(format_string<T...>, T&&...)
::: vformat(string_view, format_args)
::: operator""_a()
Utilities
::: ptr(T)
::: underlying(Enum)
::: to_string(const T&)
::: group_digits(T)
::: detail::buffer
::: basic_memory_buffer
System Errors
{fmt} does not use errno to communicate errors to the user, but it may
call system functions which set errno. Users should not make any
assumptions about the value of errno being preserved by library
functions.
::: system_error
::: format_system_error
Custom Allocators
The {fmt} library supports custom dynamic memory allocators. A custom
allocator class can be specified as a template argument to
fmt::basic_memory_buffer:
using custom_memory_buffer =
fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
It is also possible to write a formatting function that uses a custom allocator:
using custom_string =
std::basic_string<char, std::char_traits<char>, 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 <typename ...Args>
auto format(custom_allocator alloc, fmt::string_view fmt,
const Args& ... args) -> custom_string {
return vformat(alloc, fmt, fmt::make_format_args(args...));
}
The allocator will be used for the output container only. Formatting
functions normally don't do any allocations for built-in and string
types except for non-default floating-point formatting that occasionally
falls back on sprintf.
Locale
All formatting is locale-independent by default. Use the 'L' format
specifier to insert the appropriate number separator characters from the
locale:
#include <fmt/format.h>
#include <locale>
std::locale::global(std::locale("en_US.UTF-8"));
auto s = fmt::format("{:L}", 1000000); // s == "1,000,000"
fmt/format.h provides the following overloads of formatting functions
that take std::locale as a parameter. The locale type is a template
parameter to avoid the expensive <locale> include.
::: format(const Locale&, format_string<T...>, T&&...)
::: format_to(OutputIt, const Locale&, format_string<T...>, T&&...)
::: formatted_size(const Locale&, format_string<T...>, T&&...)
Legacy Compile-Time Checks
FMT_STRING enables compile-time checks on older compilers. It requires
C++14 or later and is a no-op in C++11.
::: FMT_STRING
To force the use of legacy compile-time checks, define the preprocessor
variable FMT_ENFORCE_COMPILE_STRING. When set, functions accepting
FMT_STRING will fail to compile with regular strings.
Range and Tuple Formatting
fmt/ranges.h provides formatting support for ranges and tuples:
#include <fmt/ranges.h>
fmt::print("{}", std::tuple<char, int>{'a', 42});
// Output: ('a', 42)
Using fmt::join, you can separate tuple elements with a custom separator:
#include <fmt/ranges.h>
auto t = std::tuple<int, char>{1, 'a'};
fmt::print("{}", fmt::join(t, ", "));
// Output: 1, a
::: join(Range&&, string_view)
::: join(It, Sentinel, string_view)
::: join(std::initializer_list, string_view)
Date and Time Formatting
fmt/chrono.h provides formatters for
The format syntax is described in [Chrono Format Specifications](syntax.md# chrono-format-specifications).
Example:
#include <fmt/chrono.h>
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
}
::: gmtime(std::time_t)
Standard Library Types Formatting
fmt/std.h provides formatters for:
std::atomicstd::atomic_flagstd::bitsetstd::error_codestd::exceptionstd::filesystem::pathstd::monostatestd::optionalstd::source_locationstd::thread::idstd::variant
::: ptr(const std::unique_ptr<T, Deleter>&)
::: ptr(const std::shared_ptr&)
Variants
A std::variant is only formattable if every variant alternative is
formattable, and requires the __cpp_lib_variant library
feature.
Example:
#include <fmt/std.h>
fmt::print("{}", std::variant<char, float>('x'));
// Output: variant('x')
fmt::print("{}", std::variant<std::monostate, char>());
// Output: variant(monostate)
Bit-Fields and Packed Structs
To format a bit-field or a field of a struct with __attribute__((packed))
applied to it, you need to convert it to the underlying or compatible type via
a cast or a unary + (godbolt):
struct smol {
int bit : 1;
};
auto s = smol();
fmt::print("{}", +s.bit);
This is a known limitation of "perfect" forwarding in C++.
Format String Compilation
fmt/compile.h provides format string compilation and compile-time
(constexpr) formatting enabled via the FMT_COMPILE macro or the _cf
user-defined literal defined in namespace fmt::literals. Format strings
marked with FMT_COMPILE or _cf are parsed, checked and converted into
efficient formatting code at compile-time. This supports arguments of built-in
and string types as well as user-defined types with format functions taking
the format context type as a template parameter in their formatter
specializations. For example:
template <> struct fmt::formatter<point> {
constexpr auto parse(format_parse_context& ctx);
template <typename FormatContext>
auto format(const point& p, FormatContext& ctx) const;
};
Format string compilation can generate more binary code compared to the default API and is only recommended in places where formatting is a performance bottleneck.
::: FMT_COMPILE
::: operator""_cf
Terminal Colors and Text Styles
fmt/color.h provides support for terminal color and text style output.
::: print(text_style, format_string<T...>, T&&...)
::: fg(detail::color_type)
::: bg(detail::color_type)
::: styled(const T&, text_style)
System APIs
::: ostream
::: windows_error
std::ostream Support
fmt/ostream.h provides std::ostream support including formatting of
user-defined types that have an overloaded insertion operator
(operator<<). In order to make a type formattable via std::ostream
you should provide a formatter specialization inherited from
ostream_formatter:
#include <fmt/ostream.h>
struct date {
int year, month, day;
friend std::ostream& operator<<(std::ostream& os, const date& d) {
return os << d.year << '-' << d.month << '-' << d.day;
}
};
template <> struct fmt::formatter<date> : ostream_formatter {};
std::string s = fmt::format("The date is {}", date{2012, 12, 9});
// s == "The date is 2012-12-9"
::: streamed(const T&)
::: print(std::ostream&, format_string<T...>, T&&...)
Dynamic Argument Lists
The header fmt/args.h provides dynamic_format_arg_store, a builder-like API
that can be used to construct format argument lists dynamically.
::: dynamic_format_arg_store
Safe printf
The header fmt/printf.h provides printf-like formatting
functionality. The following functions use printf format string
syntax
with the POSIX extension for positional arguments. Unlike their standard
counterparts, the fmt functions are type-safe and throw an exception
if an argument type doesn't match its format specification.
::: printf(string_view, const T&...)
::: fprintf(std::FILE*, const S&, const T&...)
::: sprintf(const S&, const T&...)
Wide Strings
The optional header fmt/xchar.h provides support for wchar_t and
exotic character types.
::: is_char
::: wstring_view
::: wformat_context
::: to_wstring(const T&)
Compatibility with C++20 std::format
{fmt} implements nearly all of the C++20 formatting library with the following differences:
-
Names are defined in the
fmtnamespace instead ofstdto avoid collisions with standard library implementations. -
Width calculation doesn't use grapheme clusterization. The latter has been implemented in a separate branch but hasn't been integrated yet.
-
The default floating-point representation in {fmt} uses the smallest precision that provides round-trip guarantees similarly to other languages like Java and Python.
std::formatis currently specified in terms ofstd::to_charswhich tries to generate the smallest number of characters (ignoring redundant digits and sign in exponent) and may procude more decimal digits than necessary.