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 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/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 compile-time checks. It has minimal include dependencies for
better compile times. This header is only beneficial when using {fmt} as a
library and not in the header-only mode.
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. A function taking fmt doesn’t
participate in an overload resolution if the latter is not a string.
args is an argument list representing objects to be formatted.
Warning
doxygenfunction: Unable to resolve multiple matches for function “format” with arguments (format_string<T…> fmt, T&&… args) -> std::strin) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename ...T>
auto fmt::format(format_string<T...>, T&&...)
- template<typename Locale, typename ...T>
auto fmt::format(const Locale&, format_string<T...>, T&&...)
- template<typename Locale, typename S, typename ...Args, typename Char = char_t<S>>
auto fmt::format(const Locale&, const S&, Args&&...)
- template<typename OutputIt>
auto fmt::detail::fallback_formatter::format(const T&, basic_format_context<OutputIt, Char>&)
- template<typename OutputIt>
auto fmt::detail::fallback_formatter::format(const T&, basic_printf_context<OutputIt, Char>&)
- template<typename S, typename ...Args, typename Char = char_t<S>>
auto fmt::format(const S&, Args&&...)
- template<typename S, typename ...Args, typename Char = char_t<S>>
std::basic_string<Char> fmt::format(const text_style&, const S&, const Args&...)
- template<typename T, typename FormatContext>
auto fmt::dynamic_formatter::format(const T&, FormatContext&)
Warning
doxygenfunction: Unable to resolve multiple matches for function “vformat” with arguments (string_view fmt, format_args args) -> std::strin) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- auto fmt::vformat(string_view, format_args)
- template<typename Char>
auto fmt::vformat(basic_string_view<Char>, basic_format_args<buffer_context<type_identity_t<Char>>>)
- template<typename Locale, typename Char>
auto fmt::detail::vformat(const Locale&, basic_string_view<Char>, basic_format_args<buffer_context<type_identity_t<Char>>>)
- template<typename Locale, typename S, typename Char = char_t<S>>
auto fmt::vformat(const Locale&, const S&, basic_format_args<buffer_context<type_identity_t<Char>>>)
- template<typename Locale>
auto fmt::vformat(const Locale&, string_view, format_args)
- template<typename S, typename Char = char_t<S>>
std::basic_string<Char> fmt::vformat(const text_style&, const S&, basic_format_args<buffer_context<type_identity_t<Char>>>)
Warning
doxygenfunction: Unable to resolve multiple matches for function “format_to” with arguments (OutputIt out, format_string<T…> fmt, T&&… args) -> OutputI) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename ...T, size_t SIZE, typename Allocator>
auto fmt::format_to(basic_memory_buffer<char, SIZE, Allocator>&, format_string<T...>, T&&...)
- template<typename OutputIt, typename ...T>
auto fmt::format_to(OutputIt, format_string<T...>, T&&...)
- template<typename OutputIt, typename Locale, typename ...T>
auto fmt::format_to(OutputIt, const Locale&, format_string<T...>, T&&...)
- template<typename OutputIt, typename Locale, typename S, typename ...Args, typename Char = char_t<S>, bool enable = detail::is_output_iterator<OutputIt, Char>::value && detail::is_locale<Locale>::value && detail::is_exotic_char<Char>::value>
auto fmt::format_to(OutputIt, const Locale&, const S&, Args&&...)
- template<typename OutputIt, typename S, typename ...Args, bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value && detail::is_string<S>::value>
auto fmt::format_to(OutputIt, const text_style&, const S&, Args&&...)
- template<typename OutputIt, typename S, typename ...Args, typename Char = char_t<S>>
auto fmt::format_to(OutputIt, const S&, Args&&...)
- template<typename S, typename ...Args, typename Char, size_t SIZE, typename Allocator>
auto fmt::format_to(basic_memory_buffer<Char, SIZE, Allocator>&, const S&, Args&&...)
Warning
doxygenfunction: Unable to resolve multiple matches for function “format_to_n” with arguments (OutputIt out, size_t n, format_string<T…> fmt, const T&… args) -> format_to_n_result<OutputIt) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename OutputIt, typename ...T>
auto fmt::format_to_n(OutputIt, size_t, format_string<T...>, const T&...)
- template<typename OutputIt, typename S, typename ...Args, typename Char = char_t<S>>
auto fmt::format_to_n(OutputIt, size_t, const S&, const Args&...)
- template<typename OutputIt, typename S, typename ...Args>
format_to_n_result<OutputIt> fmt::format_to_n(OutputIt, size_t, const S&, Args&&...)
Warning
doxygenfunction: Unable to resolve multiple matches for function “formatted_size” with arguments (format_string<T…> fmt, T&&… args) -> size_) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename ...T>
auto fmt::formatted_size(format_string<T...>, T&&...)
- template<typename S, typename ...Args, typename Char = char_t<S>>
auto fmt::formatted_size(const S&, Args&&...)
- template<typename S, typename ...Args>
size_t fmt::formatted_size(const S&, const Args&...)
-
template<typename
OutputIt
>
structformat_to_n_result
¶
Warning
doxygenfunction: Unable to resolve multiple matches for function “fmt::print” with arguments (format_string<T…> fmt, T&&… args) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename ...T>
void fmt::print(format_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(std::FILE*, format_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(std::FILE*, wformat_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(wformat_string<T...>, T&&...)
- template<typename S, typename ...Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
void fmt::print(std::basic_ostream<Char>&, const S&, Args&&...)
- template<typename S, typename ...Args>
void fmt::print(const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(const text_style&, const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(std::FILE*, const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(std::FILE*, const text_style&, const S&, const Args&...)
Warning
doxygenfunction: Unable to resolve multiple matches for function “vprint” with arguments (string_view fmt, format_args args) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename Char>
void fmt::vprint(std::basic_ostream<Char>&, basic_string_view<Char>, basic_format_args<buffer_context<type_identity_t<Char>>>)
- template<typename S, typename Char = char_t<S>>
void fmt::vprint(std::FILE*, const text_style&, const S&, basic_format_args<buffer_context<type_identity_t<Char>>>)
- void fmt::buffered_file::vprint(string_view, format_args)
- void fmt::vprint(std::FILE*, string_view, format_args)
- void fmt::vprint(std::FILE*, wstring_view, wformat_args)
- void fmt::vprint(string_view, format_args)
- void fmt::vprint(wstring_view, wformat_args)
Warning
doxygenfunction: Unable to resolve multiple matches for function “print” with arguments (std::FILE *f, format_string<T…> fmt, T&&… args) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename ...Args>
void fmt::buffered_file::print(string_view, const Args&...)
- template<typename ...T>
void fmt::ostream::print(format_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(format_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(std::FILE*, format_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(std::FILE*, wformat_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(wformat_string<T...>, T&&...)
- template<typename S, typename ...Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
void fmt::print(std::basic_ostream<Char>&, const S&, Args&&...)
- template<typename S, typename ...Args>
void fmt::print(const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(const text_style&, const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(std::FILE*, const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(std::FILE*, const text_style&, const S&, const Args&...)
- void fmt::detail::print(std::FILE*, string_view)
Warning
doxygenfunction: Unable to resolve multiple matches for function “vprint” with arguments (std::FILE *f, string_view fmt, format_args args) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename Char>
void fmt::vprint(std::basic_ostream<Char>&, basic_string_view<Char>, basic_format_args<buffer_context<type_identity_t<Char>>>)
- template<typename S, typename Char = char_t<S>>
void fmt::vprint(std::FILE*, const text_style&, const S&, basic_format_args<buffer_context<type_identity_t<Char>>>)
- void fmt::buffered_file::vprint(string_view, format_args)
- void fmt::vprint(std::FILE*, string_view, format_args)
- void fmt::vprint(std::FILE*, wstring_view, wformat_args)
- void fmt::vprint(string_view, format_args)
- void fmt::vprint(wstring_view, wformat_args)
Compile-time Format String Checks¶
Compile-time checks are enabled when using FMT_STRING
. They support 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 = fmt::format(FMT_STRING("{:d}"), "foo");
To force the use of compile-time checks, define the preprocessor variable
FMT_ENFORCE_COMPILE_STRING
. When set, functions accepting FMT_STRING
will fail to compile with regular strings. Runtime-checked
formatting is still possible using fmt::vformat
, fmt::vprint
, etc.
Named Arguments¶
-
template<typename
Char
, typenameT
>
autofmt
::
arg
(const Char *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 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/oba4Mc):
#include <fmt/format.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 S, typename... Args>
void log(const char* file, int line, const S& format, Args&&... args) {
vlog(file, line, format,
fmt::make_args_checked<Args...>(format, args...));
}
#define MY_LOG(format, ...) \
log(__FILE__, __LINE__, FMT_STRING(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 ...
Args
, typenameS
, typenameChar
= char_t<S>>
autofmt
::
make_args_checked
(const S &fmt, const remove_reference_t<Args>&... args)¶ Constructs a
format_arg_store
object that contains references to arguments and can be implicitly converted toformat_args
. Iffmt
is a compile-time string thenmake_args_checked
checks its validity at compile time.
-
template<typename
Context
= format_context, typename ...Args
>
constexpr autofmt
::
make_format_args
(const Args&... args)¶ 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
>
classdynamic_format_arg_store
¶
-
template<typename
Context
>
classbasic_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¶ 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
OutputIt
, typenameChar
>
classbasic_format_context
¶ Public Types
-
template<>
usingchar_type
= Char¶ The character type for the output.
Public Functions
-
constexpr
basic_format_context
(OutputIt out, basic_format_args<basic_format_context> ctx_args, detail::locale_ref loc = detail::locale_ref())¶ Constructs a
basic_format_context
object.References to the arguments are stored in the object so make sure they have appropriate lifetimes.
-
template<>
-
using
fmt
::
format_context
= buffer_context<char>¶
Compatibility¶
-
template<typename
Char
>
classbasic_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)¶ 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.
-
constexpr auto
data
() const¶ Returns a pointer to the string data.
-
constexpr auto
size
() const¶ Returns the string size.
-
constexpr
-
using
fmt
::
string_view
= basic_string_view<char>¶
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"
Format API¶
fmt/format.h
defines the full format API providing additional formatting
functions and locale support.
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) -> decltype(ctx.begin()) {
// [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) -> decltype(ctx.out()) {
// 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);
}
};
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:
#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"
}
If a type provides both a formatter
specialization and an implicit
conversion to a formattable type, the specialization takes precedence over the
conversion.
-
template<typename
Char
, typenameErrorHandler
= detail::error_handler>
classbasic_format_parse_context
: private fmt::detail::error_handler¶ 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::detail::compile_parse_context< Char, ErrorHandler >, fmt::basic_printf_parse_context< Char >
Public Functions
-
constexpr auto
begin
() const¶ Returns an iterator to the beginning of the format string range being parsed.
-
constexpr auto
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
.
-
auto
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.
-
constexpr auto
Literal-based API¶
The following user-defined literals are defined in fmt/format.h
.
Warning
doxygenfunction: Unable to resolve multiple matches for function “operator””_format” with arguments (const char *s, size_t n) -> detail::udl_formatter<char) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- constexpr auto fmt::literals::operator""_format(const char*, size_t)
- constexpr auto fmt::literals::operator""_format(const wchar_t*, size_t)
Warning
doxygenfunction: Unable to resolve multiple matches for function “operator””_a” with arguments (const char *s, size_t) -> detail::udl_arg<char) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- constexpr auto fmt::literals::operator""_a(const char*, size_t)
- constexpr detail::udl_arg<wchar_t> fmt::literals::operator""_a(const wchar_t*, size_t)
Utilities¶
Warning
doxygenfunction: Unable to resolve multiple matches for function “fmt::ptr” with arguments (T p) -> const void) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename T>
auto fmt::ptr(T)
- template<typename T>
auto fmt::ptr(const std::shared_ptr<T>&)
- template<typename T>
auto fmt::ptr(const std::unique_ptr<T>&)
Warning
doxygenfunction: Unable to resolve multiple matches for function “fmt::ptr” with arguments (const std::unique_ptr<T> &p) -> const void) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename T>
auto fmt::ptr(T)
- template<typename T>
auto fmt::ptr(const std::shared_ptr<T>&)
- template<typename T>
auto fmt::ptr(const std::unique_ptr<T>&)
Warning
doxygenfunction: Unable to resolve multiple matches for function “fmt::ptr” with arguments (const std::shared_ptr<T> &p) -> const void) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename T>
auto fmt::ptr(T)
- template<typename T>
auto fmt::ptr(const std::shared_ptr<T>&)
- template<typename T>
auto fmt::ptr(const std::unique_ptr<T>&)
Warning
doxygenfunction: Unable to resolve multiple matches for function “fmt::to_string” with arguments (const T &value) -> std::strin) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename Char, size_t SIZE>
auto fmt::to_string(const basic_memory_buffer<Char, SIZE>&)
- template<typename T>
auto fmt::to_string(T)
- template<typename T>
auto fmt::to_string(const T&)
Warning
doxygenfunction: Unable to resolve multiple matches for function “fmt::to_string_view” with arguments (const Char *s) -> basic_string_view<Char) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename Char, typename Traits, typename Alloc>
auto fmt::to_string_view(const std::basic_string<Char, Traits, Alloc>&)
- template<typename Char>
auto fmt::to_string_view(const Char*)
- template<typename Char>
auto fmt::to_string_view(detail::std_string_view<Char>)
- template<typename Char>
constexpr auto fmt::to_string_view(basic_string_view<Char>)
- template<typename S>
constexpr auto fmt::to_string_view(const S&)
Warning
doxygenfunction: Unable to resolve multiple matches for function “fmt::join” with arguments (Range &&range, string_view sep) -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename It, typename Sentinel>
auto fmt::join(It, Sentinel, string_view)
- template<typename It, typename Sentinel>
auto fmt::join(It, Sentinel, wstring_view)
- template<typename Range>
auto fmt::join(Range&&, string_view)
- template<typename Range>
auto fmt::join(Range&&, wstring_view)
- template<typename T>
auto fmt::join(std::initializer_list<T>, wstring_view)
Warning
doxygenfunction: Unable to resolve multiple matches for function “fmt::join” with arguments (It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename It, typename Sentinel>
auto fmt::join(It, Sentinel, string_view)
- template<typename It, typename Sentinel>
auto fmt::join(It, Sentinel, wstring_view)
- template<typename Range>
auto fmt::join(Range&&, string_view)
- template<typename Range>
auto fmt::join(Range&&, wstring_view)
- template<typename T>
auto fmt::join(std::initializer_list<T>, wstring_view)
-
template<typename
T
>
classbuffer
¶ 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< wchar_t >, fmt::basic_memory_buffer< T, SIZE, Allocator >, fmt::detail::iterator_buffer< OutputIt, T, Traits >, fmt::detail::iterator_buffer< T *, T >
-
template<typename
T
, size_tSIZE
= inline_buffer_size, typenameAllocator
= std::allocator<T>>
classbasic_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:
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.
-
auto
operator=
(basic_memory_buffer &&other)¶ 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 capacity)¶ 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)¶ 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)¶ 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) {
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. 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
.
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¶
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);
}
Warning
doxygenfunction: Unable to resolve multiple matches for function “localtime” with arguments (std::time_t time) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- std::tm fmt::localtime(std::chrono::time_point<std::chrono::system_clock>)
- std::tm fmt::localtime(std::time_t)
Warning
doxygenfunction: Unable to resolve multiple matches for function “gmtime” with arguments (std::time_t time) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- std::tm fmt::gmtime(std::chrono::time_point<std::chrono::system_clock>)
- std::tm fmt::gmtime(std::time_t)
Format string compilation¶
fmt/compile.h
provides format string compilation support when using
FMT_COMPILE
. Format strings 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);
Terminal color and text style¶
fmt/color.h
provides support for terminal color and text style output.
Warning
doxygenfunction: Unable to resolve multiple matches for function “print” with arguments (const text_style &ts, const S &format_str, const Args&… args) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename ...Args>
void fmt::buffered_file::print(string_view, const Args&...)
- template<typename ...T>
void fmt::ostream::print(format_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(format_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(std::FILE*, format_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(std::FILE*, wformat_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(wformat_string<T...>, T&&...)
- template<typename S, typename ...Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
void fmt::print(std::basic_ostream<Char>&, const S&, Args&&...)
- template<typename S, typename ...Args>
void fmt::print(const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(const text_style&, const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(std::FILE*, const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(std::FILE*, const text_style&, const S&, const Args&...)
- void fmt::detail::print(std::FILE*, string_view)
-
text_style
fmt
::
fg
(detail::color_type foreground)¶ Creates a text style from the foreground (text) color.
-
text_style
fmt
::
bg
(detail::color_type background)¶ Creates a text style from the background color.
System APIs¶
-
class
ostream
: private fmt::detail::buffer<char>¶ A fast output stream which is not thread-safe.
Public Functions
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
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<<
):
#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"
{fmt} only supports insertion operators that are defined in the same namespaces as the types they format and can be found with the argument-dependent lookup.
Warning
doxygenfunction: Unable to resolve multiple matches for function “print” with arguments (std::basic_ostream<Char> &os, const S &format_str, Args&&… args) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename ...Args>
void fmt::buffered_file::print(string_view, const Args&...)
- template<typename ...T>
void fmt::ostream::print(format_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(format_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(std::FILE*, format_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(std::FILE*, wformat_string<T...>, T&&...)
- template<typename ...T>
void fmt::print(wformat_string<T...>, T&&...)
- template<typename S, typename ...Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
void fmt::print(std::basic_ostream<Char>&, const S&, Args&&...)
- template<typename S, typename ...Args>
void fmt::print(const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(const text_style&, const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(std::FILE*, const S&, const Args&...)
- template<typename S, typename ...Args>
void fmt::print(std::FILE*, const text_style&, const S&, const Args&...)
- void fmt::detail::print(std::FILE*, string_view)
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)¶ Prints formatted data to
stdout
.Example:
fmt::printf("Elapsed time: %.2f seconds", 1.23);
Warning
doxygenfunction: Unable to resolve multiple matches for function “fprintf” with arguments (std::FILE *f, const S &fmt, const T&… args) -> in) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:
- template<typename S, typename ...T, typename Char = char_t<S>>
auto fmt::fprintf(std::FILE*, const S&, const T&...)
- template<typename S, typename ...T, typename Char = char_t<S>>
auto fmt::fprintf(std::basic_ostream<Char>&, const S&, const T&...)
wchar_t
Support¶
The optional header fmt/wchar_t.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.