API Reference¶
The {fmt} library API consists of the following parts:
fmt/core.h: the core API providing main formatting functions for
char
/UTF-8 with C++20 compile-time checks and minimal dependenciesfmt/format.h: the full format API providing additional formatting functions and locale support
fmt/ranges.h: formatting of ranges and tuples
fmt/chrono.h: date and time formatting
fmt/std.h: formatters for standard library types
fmt/compile.h: format string compilation
fmt/color.h: terminal color and text style
fmt/os.h: system APIs
fmt/ostream.h:
std::ostream
supportfmt/printf.h:
printf
formattingfmt/xchar.h: optional
wchar_t
support
All functions and types provided by the library reside in namespace fmt
and
macros have prefix FMT_
.
Core API¶
fmt/core.h
defines the core 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 built-in and string types.
The following functions use format string syntax similar to that of Python’s str.format. 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. 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.
-
template<typename ...
T
>
autofmt
::
format
(format_string<T...> fmt, T&&... args) -> std::string¶ Formats
args
according to specifications infmt
and returns the result as a string.Example:
#include <fmt/core.h> std::string message = fmt::format("The answer is {}.", 42);
-
auto
fmt
::
vformat
(string_view fmt, format_args args) -> std::string¶
-
template<typename
OutputIt
, typename ...T
>
autofmt
::
format_to
(OutputIt out, format_string<T...> fmt, T&&... args) -> OutputIt¶ Formats
args
according to specifications infmt
, writes the result to the output iteratorout
and returns the iterator past the end of the output range.format_to()
does not append a terminating null character.Example:
auto out = std::vector<char>(); fmt::format_to(std::back_inserter(out), "{}", 42);
-
template<typename
OutputIt
, typename ...T
>
autofmt
::
format_to_n
(OutputIt out, size_t n, format_string<T...> fmt, T&&... args) -> format_to_n_result<OutputIt>¶ Formats
args
according to specifications infmt
, writes up ton
characters of the result to the output iteratorout
and returns the total (not truncated) output size and the iterator past the end of the output range.format_to_n()
does not append a terminating null character.
-
template<typename ...
T
>
autofmt
::
formatted_size
(format_string<T...> fmt, T&&... args) -> size_t¶ Returns the number of chars in the output of
format(fmt, args...)
.
-
template<typename
OutputIt
>
structfmt
::
format_to_n_result
¶
-
template<typename ...
T
>
voidfmt
::
print
(format_string<T...> fmt, T&&... args)¶ Formats
args
according to specifications infmt
and writes the output tostdout
.Example:
fmt::print("Elapsed time: {0:.2f} seconds", 1.23);
-
void
fmt
::
vprint
(string_view fmt, format_args args)¶
-
template<typename ...
T
>
voidfmt
::
print
(std::FILE *f, format_string<T...> fmt, T&&... args)¶ Formats
args
according to specifications infmt
and writes the output to the filef
.Example:
fmt::print(stderr, "Don't {}!", "panic");
-
void
fmt
::
vprint
(std::FILE *f, string_view fmt, format_args args)¶
Compile-Time Format String 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.
-
template<typename
Char
, typename ...Args
>
classbasic_format_string
¶ A compile-time format string.
-
template<typename ...
Args
>
usingfmt
::
format_string
= basic_format_string<char, type_identity_t<Args>...>¶
-
auto
fmt
::
runtime
(string_view s) -> runtime_format_string<>¶ Creates a runtime format string.
Example:
// Check format string at runtime instead of compile-time. fmt::print(fmt::runtime("{:d}"), "I am not a number");
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.
To make a user-defined type formattable, specialize the formatter<T>
struct
template and implement parse
and format
methods:
#include <fmt/core.h>
struct point {
double x, y;
};
template <> struct fmt::formatter<point> {
// Presentation format: 'f' - fixed, 'e' - exponential.
char presentation = 'f';
// Parses format specifications of the form ['f' | 'e'].
constexpr auto parse(format_parse_context& ctx) -> format_parse_context::iterator {
// [ctx.begin(), ctx.end()) is a character range that contains a part of
// the format string starting from the format specifications to be parsed,
// e.g. in
//
// fmt::format("{:f} - point of interest", point{1, 2});
//
// the range will contain "f} - point of interest". 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 '}'.
// Please also note that this character range may be empty, in case of
// the "{}" format string, so therefore you should check ctx.begin()
// for equality with ctx.end().
// Parse the presentation format and store it in the formatter:
auto it = ctx.begin(), end = ctx.end();
if (it != end && (*it == 'f' || *it == 'e')) presentation = *it++;
// Check if reached the end of the range:
if (it != end && *it != '}') ctx.on_error("invalid format");
// Return an iterator past the end of the parsed range:
return it;
}
// Formats the point p using the parsed format specification (presentation)
// stored in this formatter.
auto format(const point& p, format_context& ctx) const -> format_context::iterator {
// ctx.out() is an output iterator to write to.
return presentation == 'f'
? fmt::format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y)
: fmt::format_to(ctx.out(), "({:.1e}, {:.1e})", p.x, p.y);
}
};
Then you can pass objects of type point
to any formatting function:
point p = {1, 2};
std::string s = fmt::format("{:f}", p);
// s == "(1.0, 2.0)"
You can also reuse existing formatters via inheritance or composition, for example:
// color.h:
#include <fmt/core.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;
};
// color.cc:
#include "color.h"
#include <fmt/format.h>
auto fmt::formatter<color>::format(color c, format_context& ctx) const {
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"
.
You can also write a formatter for a hierarchy of classes:
// demo.h:
#include <type_traits>
#include <fmt/core.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<A, T>::value, char>> :
fmt::formatter<std::string> {
auto format(const A& a, format_context& ctx) const {
return fmt::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); // prints "B"
}
If a type provides both a formatter
specialization and an implicit
conversion to a formattable type, the specialization takes precedence over the
conversion.
For enums {fmt} also provides the format_as
extension API. To format an enum
via this API define format_as
that takes this enum and converts it to the
underlying type. format_as
should be defined in the same namespace as the
enum.
Example (https://godbolt.org/z/r7vvGE1v7):
#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); // prints "7"
}
Named Arguments¶
-
template<typename
Char
, typenameT
>
autofmt
::
arg
(const Char *name, const T &arg) -> detail::named_arg<Char, T>¶ Returns a named argument to be used in a formatting function. It should only be used in a call to a formatting function or
dynamic_format_arg_store::push_back()
.Example:
fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23));
Named arguments are not supported in compile-time checks at the moment.
Argument Lists¶
You can create your own formatting function with compile-time checks and small binary footprint, for example (https://godbolt.org/z/vajfWEG4b):
#include <fmt/core.h>
void vlog(const char* file, int line, fmt::string_view format,
fmt::format_args args) {
fmt::print("{}: {}: ", file, line);
fmt::vprint(format, args);
}
template <typename... T>
void log(const char* file, int line, fmt::format_string<T...> format, T&&... args) {
vlog(file, line, format, fmt::make_format_args(args...));
}
#define MY_LOG(format, ...) log(__FILE__, __LINE__, format, __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.
-
template<typename
Context
= format_context, typename ...T
>
constexpr autofmt
::
make_format_args
(T&&... args) -> format_arg_store<Context, remove_cvref_t<T>...>¶ Constructs a
format_arg_store
object that contains references to arguments and can be implicitly converted toformat_args
.Context
can be omitted in which case it defaults tocontext
. Seearg()
for lifetime considerations.
-
template<typename
Context
, typename ...Args
>
classformat_arg_store
¶ An array of references to arguments. It can be implicitly converted into
basic_format_args
for passing into type-erased formatting functions such asvformat()
.
-
template<typename
Context
>
classfmt
::
dynamic_format_arg_store
¶ A dynamic version of
fmt::format_arg_store
. It’s equipped with a storage to potentially temporary objects which lifetimes could be shorter than the format arguments object.It can be implicitly converted into
basic_format_args
for passing into type-erased formatting functions such asvformat()
.Public Functions
-
template<typename
T
>
voidpush_back
(const T &arg)¶ Adds an argument into the dynamic store for later passing to a formatting function.
Note that custom types and string types (but not string views) are copied into the store dynamically allocating memory if necessary.
Example:
fmt::dynamic_format_arg_store<fmt::format_context> store; store.push_back(42); store.push_back("abc"); store.push_back(1.5f); std::string result = fmt::vformat("{} and {} and {}", store);
-
template<typename
T
>
voidpush_back
(std::reference_wrapper<T> arg)¶ Adds a reference to the argument into the dynamic store for later passing to a formatting function.
Example:
fmt::dynamic_format_arg_store<fmt::format_context> store; char band[] = "Rolling Stones"; store.push_back(std::cref(band)); band[9] = 'c'; // Changing str affects the output. std::string result = fmt::vformat("{}", store); // result == "Rolling Scones"
-
template<typename
T
>
voidpush_back
(const detail::named_arg<char_type, T> &arg)¶ Adds named argument into the dynamic store for later passing to a formatting function.
std::reference_wrapper
is supported to avoid copying of the argument. The name is always copied into the store.
-
void
clear
()¶ Erase all elements from the store.
-
void
reserve
(size_t new_cap, size_t new_cap_named)¶ Reserves space to store at least new_cap arguments including new_cap_named named arguments.
-
template<typename
-
template<typename
Context
>
classfmt
::
basic_format_args
¶ A view of a collection of formatting arguments. To avoid lifetime issues it should only be used as a parameter type in type-erased functions such as
vformat
:void vlog(string_view format_str, format_args args); // OK format_args args = make_format_args(42); // Error: dangling reference
Public Functions
-
template<typename ...
Args
>
constexprbasic_format_args
(const format_arg_store<Context, Args...> &store)¶ Constructs a
basic_format_args()
object fromformat_arg_store
.
-
constexpr
basic_format_args
(const dynamic_format_arg_store<Context> &store)¶ Constructs a
basic_format_args()
object fromdynamic_format_arg_store
.
-
constexpr
basic_format_args
(const format_arg *args, int count)¶ Constructs a
basic_format_args()
object from a dynamic set of arguments.
-
auto
get
(int id) const -> format_arg¶ Returns the argument with the specified id.
-
template<typename ...
-
using
fmt
::
format_args
= basic_format_args<format_context>¶ An alias to
basic_format_args<format_context>
.
-
template<typename
Context
>
classbasic_format_arg
¶
-
template<typename
Char
>
classfmt
::
basic_format_parse_context
¶ Parsing context consisting of a format string range being parsed and an argument counter for automatic indexing. You can use the
format_parse_context
type alias forchar
instead.Subclassed by fmt::basic_printf_parse_context< Char >, fmt::detail::compile_parse_context< Char >
Public Functions
-
constexpr auto
begin
() const noexcept -> iterator¶ Returns an iterator to the beginning of the format string range being parsed.
-
constexpr auto
end
() const noexcept -> iterator¶ Returns an iterator past the end of the format string range being parsed.
-
void
advance_to
(iterator it)¶ Advances the begin iterator to
it
.
-
auto
next_arg_id
() -> int¶ Reports an error if using the manual argument indexing; otherwise returns the next argument index and switches to the automatic indexing.
-
void
check_arg_id
(int id)¶ Reports an error if using the automatic argument indexing; otherwise switches to the manual indexing.
-
constexpr auto
-
template<typename
OutputIt
, typenameChar
>
classfmt
::
basic_format_context
¶ -
Public Functions
-
constexpr
basic_format_context
(OutputIt out, format_args ctx_args, detail::locale_ref loc = {})¶ Constructs a
basic_format_context
object.References to the arguments are stored in the object so make sure they have appropriate lifetimes.
-
constexpr
-
using
fmt
::
format_context
= buffer_context<char>¶
Compatibility¶
-
template<typename
Char
>
classfmt
::
basic_string_view
¶ An implementation of
std::basic_string_view
for pre-C++17.It provides a subset of the API.
fmt::basic_string_view
is used for format strings even ifstd::string_view
is available to prevent issues when a library is compiled with a different-std
option than the client code (which is not recommended).Public Functions
-
constexpr
basic_string_view
(const Char *s, size_t count) noexcept¶ Constructs a string reference object from a C string and a size.
-
basic_string_view
(const Char *s)¶ Constructs a string reference object from a C string computing the size with
std::char_traits<Char>::length
.
-
template<typename
Traits
, typenameAlloc
>basic_string_view
(const std::basic_string<Char, Traits, Alloc> &s) noexcept¶ Constructs a string reference from a
std::basic_string
object.
-
constexpr auto
size
() const noexcept -> size_t¶ Returns the string size.
-
constexpr
-
using
fmt
::
string_view
= basic_string_view<char>¶
Format API¶
fmt/format.h
defines the full format API providing additional formatting
functions and locale support.
Literal-Based API¶
The following user-defined literals are defined in fmt/format.h
.
-
template<detail_exported::fixed_string
Str
>
constexpr autofmt
::
operator""_a
()¶ User-defined literal equivalent of
fmt::arg()
.Example:
using namespace fmt::literals; fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);
Utilities¶
-
template<typename
T
>
autofmt
::
ptr
(T p) -> const void*¶ Converts
p
toconst void*
for pointer formatting.Example:
auto s = fmt::format("{}", fmt::ptr(p));
-
template<typename
T
, typenameDeleter
>
autofmt
::
ptr
(const std::unique_ptr<T, Deleter> &p) -> const void*¶
-
template<typename
Enum
>
constexpr autofmt
::
underlying
(Enum e) noexcept -> underlying_t<Enum>¶ Converts
e
to the underlying type.Example:
enum class color { red, green, blue }; auto s = fmt::format("{}", fmt::underlying(color::red));
-
template<typename
T
>
autofmt
::
to_string
(const T &value) -> std::string¶ Converts value to
std::string
using the default format for type T.Example:
#include <fmt/format.h> std::string answer = fmt::to_string(42);
-
template<typename
Range
>
autofmt
::
join
(Range &&range, string_view sep) -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>>¶ Returns a view that formats
range
with elements separated bysep
.Example:
std::vector<int> v = {1, 2, 3}; fmt::print("{}", fmt::join(v, ", ")); // Output: "1, 2, 3"
fmt::join
applies passed format specifiers to the range elements:fmt::print("{:02}", fmt::join(v, ", ")); // Output: "01, 02, 03"
-
template<typename
It
, typenameSentinel
>
autofmt
::
join
(It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel>¶ Returns a view that formats the iterator range
[begin, end)
with elements separated bysep
.
-
template<typename
T
>
autofmt
::
group_digits
(T value) -> group_digits_view<T>¶ Returns a view that formats an integer value using ‘,’ as a locale-independent thousands separator.
Example:
fmt::print("{}", fmt::group_digits(12345)); // Output: "12,345"
-
template<typename
T
>
classfmt::detail
::
buffer
¶ A contiguous memory buffer with an optional growing ability. It is an internal class and shouldn’t be used directly, only via
basic_memory_buffer
.Subclassed by fmt::basic_memory_buffer< bigit, bigits_capacity >, fmt::basic_memory_buffer< wchar_t >, fmt::basic_memory_buffer< T, SIZE, Allocator >, fmt::detail::counting_buffer< T >, fmt::detail::iterator_buffer< OutputIt, T, Traits >, fmt::detail::iterator_buffer< T *, T >, fmt::detail::iterator_buffer< T *, T, fixed_buffer_traits >
-
template<typename
T
, size_tSIZE
= inline_buffer_size, typenameAllocator
= std::allocator<T>>
classfmt
::
basic_memory_buffer
: public fmt::detail::buffer<T>¶ A dynamically growing memory buffer for trivially copyable/constructible types with the first
SIZE
elements stored in the object itself.You can use the
memory_buffer
type alias forchar
instead.Example:
auto out = fmt::memory_buffer(); format_to(std::back_inserter(out), "The answer is {}.", 42);
This will append the following output to the
out
object:The answer is 42.
The output can be converted to an
std::string
withto_string(out)
.Public Functions
-
basic_memory_buffer
(basic_memory_buffer &&other) noexcept¶ Constructs a
fmt::basic_memory_buffer
object moving the content of the other object to it.
-
auto
operator=
(basic_memory_buffer &&other) noexcept -> basic_memory_buffer&¶ Moves the content of the other
basic_memory_buffer
object to this one.
-
void
resize
(size_t count)¶ Resizes the buffer to contain count elements.
If T is a POD type new elements may not be initialized.
-
void
reserve
(size_t new_capacity)¶ Increases the buffer capacity to new_capacity.
Protected Functions
-
void
grow
(size_t size) override¶ Increases the buffer capacity to hold at least capacity elements.
-
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.
-
template<typename ...
T
>
autofmt
::
system_error
(int error_code, format_string<T...> fmt, T&&... args) -> std::system_error¶ Constructs
std::system_error
with a message formatted withfmt::format(fmt, args...)
.error_code is a system error code as given by
errno
.Example:
// This throws std::system_error with the description // cannot open file 'madeup': No such file or directory // or similar (system message may vary). const char* filename = "madeup"; std::FILE* file = std::fopen(filename, "r"); if (!file) throw fmt::system_error(errno, "cannot open file '{}'", filename);
-
void
fmt
::
format_system_error
(detail::buffer<char> &out, int error_code, const char *message) noexcept¶ Formats an error message for an error returned by an operating system or a language runtime, for example a file opening error, and writes it to out. The format is the same as the one used by
std::system_error(ec, message)
whereec
isstd::error_code(error_code, std::generic_category()})
. It is implementation-defined but normally looks like:<message>: <system-message>
where <message> is the passed message and <system-message> is the system message corresponding to the error code. error_code is a system error code as given by
errno
.
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>;
custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
fmt::format_args args) {
auto buf = custom_memory_buffer(alloc);
fmt::vformat_to(std::back_inserter(buf), format_str, args);
return custom_string(buf.data(), buf.size(), alloc);
}
template <typename ...Args>
inline custom_string format(custom_allocator alloc,
fmt::string_view format_str,
const Args& ... args) {
return vformat(alloc, format_str, 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/core.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.
-
template<typename
Locale
, typename ...T
>
autofmt
::
format
(const Locale &loc, format_string<T...> fmt, T&&... args) -> std::string¶
Legacy Compile-Time Format String 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
(s)¶ Constructs a compile-time format string from a string literal s.
Example:
// A compile-time error because 'd' is an invalid specifier for strings. std::string s = fmt::format(FMT_STRING("{:d}"), "foo");
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¶
The library also supports convenient formatting of ranges and tuples:
#include <fmt/ranges.h>
std::tuple<char, int, float> t{'a', 1, 2.0f};
// Prints "('a', 1, 2.0)"
fmt::print("{}", t);
NOTE: currently, the overload of fmt::join
for iterables exists in the main
format.h
header, but expect this to change in the future.
Using fmt::join
, you can separate tuple elements with a custom separator:
#include <fmt/ranges.h>
std::tuple<int, char> t = {1, 'a'};
// Prints "1, a"
fmt::print("{}", fmt::join(t, ", "));
Date and Time Formatting¶
fmt/chrono.h
provides formatters for
The format syntax is described in Chrono Format Specifications.
Example:
#include <fmt/chrono.h>
int main() {
std::time_t t = std::time(nullptr);
// Prints "The date is 2020-11-07." (with the current date):
fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t));
using namespace std::literals::chrono_literals;
// Prints "Default format: 42s 100ms":
fmt::print("Default format: {} {}\n", 42s, 100ms);
// Prints "strftime-like format: 03:15:30":
fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
}
-
std::tm
fmt
::
localtime
(std::time_t time)¶ Converts given time since epoch as
std::time_t
value into calendar time, expressed in local time.Unlike
std::localtime
, this function is thread-safe on most platforms.
-
std::tm
fmt
::
gmtime
(std::time_t time)¶ Converts given time since epoch as
std::time_t
value into calendar time, expressed in Coordinated Universal Time (UTC).Unlike
std::gmtime
, this function is thread-safe on most platforms.
Standard Library Types Formatting¶
fmt/std.h
provides formatters for:
Formatting 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>
std::variant<char, float> v0{'x'};
// Prints "variant('x')"
fmt::print("{}", v0);
std::variant<std::monostate, char> v1;
// Prints "variant(monostate)"
Format String Compilation¶
fmt/compile.h
provides format string compilation enabled via the
FMT_COMPILE
macro or the _cf
user-defined literal. 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 constexpr
parse
functions in their formatter
specializations. 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
(s)¶ Converts a string literal s into a format string that will be parsed at compile time and converted into efficient formatting code. Requires C++17
constexpr if
compiler support.Example:
// Converts 42 into std::string using the most efficient method and no // runtime format string processing. std::string s = fmt::format(FMT_COMPILE("{}"), 42);
-
template<detail_exported::fixed_string
Str
>
constexpr autofmt
::
operator""_cf
()¶
Terminal Color and Text Style¶
fmt/color.h
provides support for terminal color and text style output.
-
template<typename
S
, typename ...Args
>
voidfmt
::
print
(const text_style &ts, const S &format_str, const Args&... args)¶ Formats a string and prints it to stdout using ANSI escape sequences to specify text formatting.
Example:
fmt::print(fmt::emphasis::bold | fg(fmt::color::red), "Elapsed time: {0:.2f} seconds", 1.23);
-
text_style
fmt
::
fg
(detail::color_type foreground) noexcept¶ Creates a text style from the foreground (text) color.
-
text_style
fmt
::
bg
(detail::color_type background) noexcept¶ Creates a text style from the background color.
-
template<typename
T
>
autofmt
::
styled
(const T &value, text_style ts) -> detail::styled_arg<remove_cvref_t<T>>¶ Returns an argument that will be formatted using ANSI escape sequences, to be used in a formatting function.
Example:
fmt::print("Elapsed time: {0:.2f} seconds", fmt::styled(1.23, fmt::fg(fmt::color::green) | fmt::bg(fmt::color::blue)));
System APIs¶
-
class
fmt
::
ostream
¶ A fast output stream which is not thread-safe.
Public Functions
-
template<typename ...
T
>
voidprint
(format_string<T...> fmt, T&&... args)¶ Formats
args
according to specifications infmt
and writes the output to the file.
Friends
-
template<typename ...
T
>
ostreamoutput_file
(cstring_view path, T... params)¶ Opens a file for writing. Supported parameters passed in params:
<integer>
: Flags passed to open (file::WRONLY | file::CREATE | file::TRUNC
by default)buffer_size=<integer>
: Output buffer size
Example:
auto out = fmt::output_file("guide.txt"); out.print("Don't {}", "Panic");
-
template<typename ...
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"
-
template<typename
T
>
autofmt
::
streamed
(const T &value) -> detail::streamed_view<T>¶ Returns a view that formats
value
via an ostreamoperator<<
.Example:
fmt::print("Current thread id: {}\n", fmt::streamed(std::this_thread::get_id()));
-
template<typename ...
T
>
voidfmt
::
print
(std::ostream &os, format_string<T...> fmt, T&&... args)¶ Prints formatted data to the stream os.
Example:
fmt::print(cerr, "Don't {}!", "panic");
printf
Formatting¶
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.
-
template<typename
S
, typename ...T
>
autofmt
::
printf
(const S &fmt, const T&... args) -> int¶ Prints formatted data to
stdout
.Example:
fmt::printf("Elapsed time: %.2f seconds", 1.23);
-
template<typename
S
, typename ...T
, typenameChar
= char_t<S>>
autofmt
::
fprintf
(std::FILE *f, const S &fmt, const T&... args) -> int¶ Prints formatted data to the file f.
Example:
fmt::fprintf(stderr, "Don't %s!", "panic");
-
template<typename
S
, typename ...T
, typenameChar
= enable_if_t<detail::is_string<S>::value, char_t<S>>>
autofmt
::
sprintf
(const S &fmt, const T&... args) -> std::basic_string<Char>¶ Formats arguments and returns the result as a string.
Example:
std::string message = fmt::sprintf("The answer is %d", 42);
wchar_t
Support¶
The optional header fmt/xchar.h
provides support for wchar_t
and exotic
character types.
-
template<typename
T
>
structis_char
: public std::false_type¶ Specifies if
T
is a character type.Can be specialized by users.
-
using
fmt
::
wstring_view
= basic_string_view<wchar_t>¶
-
using
fmt
::
wformat_context
= buffer_context<wchar_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
fmt
namespace instead ofstd
to 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.
Most C++20 chrono types are not supported yet.