API Reference¶
The {fmt} library API consists of the following parts:
fmt/core.h: the core API providing argument handling facilities and a lightweight subset of formatting functions
fmt/format.h: the full format API providing compile-time format string checks, output iterator and user-defined type support
fmt/ranges.h: additional formatting support for ranges and tuples
fmt/chrono.h: date and time formatting
fmt/ostream.h:
std::ostream
supportfmt/printf.h:
printf
formatting
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 argument handling facilities
and a lightweight subset of formatting functions. In the header-only mode
include fmt/format.h
instead of fmt/core.h
.
The following functions use format string syntax similar to that of Python’s str.format. They take format_str and args as arguments.
format_str 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. A function taking format_str doesn’t
participate in an overload resolution if the latter is not a string.
args is an argument list representing objects to be formatted.
-
template<typename
S
, typename ...Args
, typenameChar
= char_t<S>>
std::basic_string<Char>fmt
::
format
(const S &format_str, Args&&... args)¶ Formats arguments and returns the result as a string.
Example:
#include <fmt/core.h> std::string message = fmt::format("The answer is {}", 42);
-
template<typename
S
, typenameChar
= char_t<S>>
std::basic_string<Char>fmt
::
vformat
(const S &format_str, basic_format_args<buffer_context<type_identity_t<Char>>> args)¶
-
template<typename
S
, typename ...Args
, typenameChar
= char_t<S>>
voidfmt
::
print
(const S &format_str, Args&&... args)¶ Formats
args
according to specifications informat_str
and writes the output tostdout
. Strings are assumed to be Unicode-encoded unless theFMT_UNICODE
macro is set to 0.Example:
fmt::print("Elapsed time: {0:.2f} seconds", 1.23);
-
void
fmt::buffered_file
::
vprint
(string_view format_str, format_args args)¶
-
template<typename
S
, typename ...Args
, typenameChar
= char_t<S>>
voidfmt
::
print
(std::FILE *f, const S &format_str, Args&&... args)¶ Formats
args
according to specifications informat_str
and writes the output to the filef
. Strings are assumed to be Unicode-encoded unless theFMT_UNICODE
macro is set to 0.Example:
fmt::print(stderr, "Don't {}!", "panic");
-
void
fmt
::
vprint
(std::FILE*, string_view, format_args)¶
Named Arguments¶
-
template<typename
S
, typenameT
, typenameChar
= char_t<S>>
internal::named_arg<T, Char>fmt
::
arg
(const S &name, const T &arg)¶ Returns a named argument to be used in a formatting function. It should only be used in a call to a formatting function.
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¶
-
template<typename
Context
= format_context, typename ...Args
>
format_arg_store<Context, Args...>fmt
::
make_format_args
(const Args&... args)¶ Constructs an
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
::
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
Subclassed by fmt::format_args, fmt::wformat_args
Public Functions
-
template<typename ...
Args
>basic_format_args
(const format_arg_store<Context, Args...> &store)¶ Constructs a
basic_format_args()
object fromformat_arg_store
.
-
basic_format_args
(const dynamic_format_arg_store<Context> &store)¶ Constructs a
basic_format_args()
object fromdynamic_format_arg_store
.
-
basic_format_args
(const format_arg *args, int count)¶ Constructs a
basic_format_args()
object from a dynamic set of arguments.
-
format_arg
get
(int index) const¶ Returns the argument at specified index.
-
template<typename ...
-
struct
format_args
: public fmt::basic_format_args<format_context>¶ An alias to
basic_format_args<context>
.
-
template<typename
Context
>
classbasic_format_arg
¶
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).Subclassed by fmt::u8string_view
Public Functions
-
basic_string_view
(const Char *s, size_t count)¶ 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)¶ Constructs a string reference from a
std::basic_string
object.
-
size_t
size
() const¶ Returns the string size.
-
-
using
fmt
::
string_view
= basic_string_view<char>¶
-
using
fmt
::
wstring_view
= basic_string_view<wchar_t>¶
Locale¶
All formatting is locale-independent by default. Use the 'n'
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("{:n}", 1000000); // s == "1,000,000"
Format API¶
fmt/format.h
defines the full format API providing compile-time format
string checks, output iterator and user-defined type support.
Compile-time Format String Checks¶
Compile-time checks are supported for built-in and string types as well as
user-defined types with constexpr
parse
functions in their formatter
specializations.
-
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 = format(FMT_STRING("{:d}"), "foo");
Formatting User-defined Types¶
To make a user-defined type formattable, specialize the formatter<T>
struct
template and implement parse
and format
methods:
#include <fmt/format.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) {
// [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 '}'.
// 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 != '}')
throw format_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.
template <typename FormatContext>
auto format(const point& p, FormatContext& ctx) {
// ctx.out() is an output iterator to write to.
return format_to(
ctx.out(),
presentation == 'f' ? "({:.1f}, {:.1f})" : "({:.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:
enum class color {red, green, blue};
template <>
struct fmt::formatter<color>: formatter<string_view> {
// parse is inherited from formatter<string_view>.
template <typename FormatContext>
auto format(color c, FormatContext& ctx) {
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);
}
};
You can also write a formatter for a hierarchy of classes:
#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<A, T>::value, char>> :
fmt::formatter<std::string> {
template <typename FormatCtx>
auto format(const A& a, FormatCtx& ctx) {
return fmt::formatter<std::string>::format(a.name(), ctx);
}
};
int main() {
B b;
A& a = b;
fmt::print("{}", a); // prints "B"
}
-
template<typename
Char
, typenameErrorHandler
= internal::error_handler>
classfmt
::
basic_format_parse_context
: private fmt::internal::error_handler¶ Parsing context consisting of a format string range being parsed and an argument counter for automatic indexing.
You can use one of the following type aliases for common character types:
Type
Definition
format_parse_context
basic_format_parse_context<char>
wformat_parse_context
basic_format_parse_context<wchar_t>
Subclassed by fmt::basic_printf_parse_context< Char >
Public Functions
-
iterator
begin
() const¶ Returns an iterator to the beginning of the format string range being parsed.
-
iterator
end
() const¶ Returns an iterator past the end of the format string range being parsed.
-
void
advance_to
(iterator it)¶ Advances the begin iterator to
it
.
-
int
next_arg_id
()¶ 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)¶ Reports an error if using the automatic argument indexing; otherwise switches to the manual indexing.
-
iterator
Output Iterator Support¶
-
template<typename
OutputIt
, typenameS
, typename ...Args
>
OutputItfmt
::
format_to
(OutputIt out, const S &format_str, Args&&... args)¶ Formats arguments, writes the result to the output iterator
out
and returns the iterator past the end of the output range.Example:
std::vector<char> out; fmt::format_to(std::back_inserter(out), "{}", 42);
-
template<typename
OutputIt
, typenameS
, typename ...Args
>
format_to_n_result<OutputIt>fmt
::
format_to_n
(OutputIt out, std::size_t n, const S &format_str, const Args&... args)¶ Formats arguments, writes up to
n
characters of the result to the output iteratorout
and returns the total output size and the iterator past the end of the output range.
-
template<typename
OutputIt
>
structfmt
::
format_to_n_result
¶
Literal-based API¶
The following user-defined literals are defined in fmt/format.h
.
-
internal::udl_formatter<char>
fmt
::
operator""_format
(const char *s, std::size_t n)¶ User-defined literal equivalent of
fmt::format()
.Example:
using namespace fmt::literals; std::string message = "The answer is {}"_format(42);
-
internal::udl_arg<char>
fmt
::
operator""_a
(const char *s, std::size_t n)¶ 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
>
structis_char
: public std::false_type¶ Specifies if
T
is a character type.Can be specialized by users.
-
template<typename
S
>
usingfmt
::
char_t
= typename internal::char_t_impl<S>::type¶ String’s character type.
-
template<typename ...
Args
>
std::size_tfmt
::
formatted_size
(string_view format_str, const Args&... args)¶ Returns the number of characters in the output of
format(format_str, args...)
.
-
template<typename
T
>
std::stringfmt
::
to_string
(const T &value)¶ 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
T
>
std::wstringfmt
::
to_wstring
(const T &value)¶ Converts value to
std::wstring
using the default format for type T.
-
template<typename
Char
>
basic_string_view<Char>fmt
::
to_string_view
(const Char *s)¶ Returns a string view of
s
. In order to add custom string type support to {fmt} provide an overload ofto_string_view()
for it in the same namespace as the type for the argument-dependent lookup to work.Example:
namespace my_ns { inline string_view to_string_view(const my_string& s) { return {s.data(), s.length()}; } } std::string message = fmt::format(my_string("The answer is {}"), 42);
-
template<typename
Range
>
arg_join<internal::iterator_t<const Range>, char>fmt
::
join
(const Range &range, string_view sep)¶ Returns an object 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
>
arg_join<It, char>fmt
::
join
(It begin, It end, string_view sep)¶ Returns an object that formats the iterator range
[begin, end)
with elements separated bysep
.
-
template<typename
T
, std::size_tSIZE
= inline_buffer_size, typenameAllocator
= std::allocator<T>>
classfmt
::
basic_memory_buffer
: private std::allocator<T>, public fmt::internal::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 one of the following type aliases for common character types:
Type
Definition
memory_buffer
basic_memory_buffer<char>
wmemory_buffer
basic_memory_buffer<wchar_t>
Example:
fmt::memory_buffer out; format_to(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)¶ Constructs a
fmt::basic_memory_buffer
object moving the content of the other object to it.
-
basic_memory_buffer &
operator=
(basic_memory_buffer &&other)¶ Moves the content of the other
basic_memory_buffer
object to this one.
Protected Functions
-
void
grow
(std::size_t size)¶ 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.
-
class
fmt
::
system_error
: public std::runtime_error¶ An error returned by an operating system or a language runtime, for example a file opening error.
Subclassed by fmt::windows_error
Public Functions
-
template<typename ...
Args
>system_error
(int error_code, string_view message, const Args&... args)¶ Constructs a
fmt::system_error
object with a description formatted withfmt::format_system_error()
. message and additional arguments passed into the constructor are formatted similarly tofmt::format()
.Example:
// This throws a 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);
-
template<typename ...
-
void
fmt
::
format_system_error
(internal::buffer<char> &out, int error_code, string_view message)¶ Formats an error returned by an operating system or a language runtime, for example a file opening error, and writes it to out in the following form:
<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
. If error_code is not a valid error code such as -1, the system message may look like “Unknown error -1” and is platform-dependent.
-
class
fmt
::
windows_error
: public fmt::system_error¶ A Windows error.
Public Functions
-
template<typename ...
Args
>windows_error
(int error_code, string_view message, const Args&... args)¶ Constructs a
fmt::windows_error
object with the description of the form<message>: <system-message>
where <message> is the formatted message and <system-message> is the system message corresponding to the error code. error_code is a Windows error code as given by
GetLastError
. If error_code is not a valid error code such as -1, the system message will look like “error -1”.Example:
// This throws a windows_error with the description // cannot open file 'madeup': The system cannot find the file specified. // or similar (system message may vary). const char *filename = "madeup"; LPOFSTRUCT of = LPOFSTRUCT(); HFILE file = OpenFile(filename, &of, OF_READ); if (file == HFILE_ERROR) { throw fmt::windows_error(GetLastError(), "cannot open file '{}'", filename); }
-
template<typename ...
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) {
custom_memory_buffer buf(alloc);
fmt::vformat_to(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. If you are using named
arguments, the container that stores pointers to them will be allocated using
the default allocator. Also floating-point formatting falls back on sprintf
which may do allocations.
Custom Formatting of Built-in Types¶
It is possible to change the way arguments are formatted by providing a custom argument formatter class:
using arg_formatter = fmt::arg_formatter<fmt::buffer_range<char>>;
// A custom argument formatter that formats negative integers as unsigned
// with the ``x`` format specifier.
class custom_arg_formatter : public arg_formatter {
public:
custom_arg_formatter(fmt::format_context& ctx,
fmt::format_parse_context* parse_ctx = nullptr,
fmt::format_specs* spec = nullptr)
: arg_formatter(ctx, parse_ctx, spec) {}
using arg_formatter::operator();
auto operator()(int value) {
if (specs() && specs()->type == 'x')
return (*this)(static_cast<unsigned>(value)); // convert to unsigned and format
return arg_formatter::operator()(value);
}
};
std::string custom_vformat(fmt::string_view format_str, fmt::format_args args) {
fmt::memory_buffer buffer;
// Pass custom argument formatter as a template arg to vformat_to.
fmt::vformat_to<custom_arg_formatter>(buffer, format_str, args);
return fmt::to_string(buffer);
}
template <typename ...Args>
inline std::string custom_format(
fmt::string_view format_str, const Args&... args) {
return custom_vformat(format_str, fmt::make_format_args(args...));
}
std::string s = custom_format("{:x}", -42); // s == "ffffffd6"
-
template<typename
Range
>
classfmt
::
arg_formatter
: public fmt::internal::arg_formatter_base<Range>¶ The default argument formatter.
Public Functions
-
arg_formatter
(context_type &ctx, basic_format_parse_context<char_type> *parse_ctx = nullptr, format_specs *specs = nullptr)¶ Constructs an argument formatter object. ctx is a reference to the formatting context, specs contains format specifier information for standard argument types.
-
iterator
operator()
(typename basic_format_arg<context_type>::handle handle)¶ Formats an argument of a user-defined type.
-
Ranges 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¶
The library supports strftime-like date and time formatting:
#include <fmt/chrono.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));
The format string syntax is described in the documentation of strftime.
std::ostream
Support¶
fmt/ostream.h
provides std::ostream
support including formatting of
user-defined types that have overloaded operator<<
:
#include <fmt/ostream.h>
class date {
int year_, month_, day_;
public:
date(int year, int month, int day): year_(year), month_(month), day_(day) {}
friend std::ostream& operator<<(std::ostream& os, const date& d) {
return os << d.year_ << '-' << d.month_ << '-' << d.day_;
}
};
std::string s = fmt::format("The date is {}", date(2012, 12, 9));
// s == "The date is 2012-12-9"
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 ...Args
>
intfmt
::
printf
(const S &format_str, const Args&... args)¶ Prints formatted data to
stdout
.Example:
fmt::printf("Elapsed time: %.2f seconds", 1.23);
-
template<typename
S
, typename ...Args
, typenameChar
= enable_if_t<internal::is_string<S>::value, char_t<S>>>
intfmt
::
fprintf
(std::FILE *f, const S &format, const Args&... args)¶ Prints formatted data to the file f.
Example:
fmt::fprintf(stderr, "Don't %s!", "panic");
-
template<typename
S
, typename ...Args
, typenameChar
= char_t<S>>
intfmt
::
fprintf
(std::basic_ostream<Char> &os, const S &format_str, const Args&... args)¶ Prints formatted data to the stream os.
Example:
fmt::fprintf(cerr, "Don't %s!", "panic");
-
template<typename
S
, typename ...Args
, typenameChar
= enable_if_t<internal::is_string<S>::value, char_t<S>>>
std::basic_string<Char>fmt
::
sprintf
(const S &format, const Args&... args)¶ Formats arguments and returns the result as a string.
Example:
std::string message = fmt::sprintf("The answer is %d", 42);