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, wide string, 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/compile.h: format string compilation
fmt/color.h: terminal color and text style
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
OutputIt
, typenameS
, typename ...Args
, boolenable
= detail::is_output_iterator<OutputIt, char_t<S>>::value>
autofmt
::
format_to
(OutputIt out, const S &format_str, Args&&... args) -> typename std::enable_if<enable, OutputIt>::type¶ 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, size_t n, const S&, const Args&... args)¶
-
template<typename ...
Args
>
size_tfmt
::
formatted_size
(string_view format_str, Args&&... args)¶ Returns the number of characters in the output of
format(format_str, 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
Char
, typenameT
>
detail::named_arg<Char, T>fmt
::
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.
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 &format_str, const remove_reference_t<Args>&... args) -> format_arg_store<buffer_context<Char>, remove_reference_t<Args>...>¶ Constructs a
format_arg_store
object that contains references to arguments and can be implicitly converted toformat_args
. Ifformat_str
is a compile-time string thenmake_args_checked()
checks its validity at compile time.
-
template<typename
Context
= format_context, typename ...Args
>
format_arg_store<Context, Args...>fmt
::
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
>
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. Supports named arguments wrapped in
std::reference_wrapper
viastd::ref()
/std::cref()
.Example:
fmt::dynamic_format_arg_store<fmt::format_context> store; char str[] = "1234567890"; store.push_back(std::cref(str)); int a1_val{42}; auto a1 = fmt::arg("a1_", a1_val); store.push_back(std::cref(a1)); // Changing str affects the output but only for string and custom types. str[0] = 'X'; std::string result = fmt::vformat("{} and {a1_}"); assert(result == "X234567890 and 42");
-
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.
-
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
>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 id) const¶ Returns the argument with the specified id.
-
template<typename ...
-
struct
format_args
: public fmt::basic_format_args<format_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).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 size_t
size
() const¶ Returns the string size.
-
constexpr
-
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 '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 compile-time format
string checks, wide string, output iterator and user-defined type support.
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");
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) {
// auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) // c++11
// [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) {
// auto format(const point &p, FormatContext &ctx) -> decltype(ctx.out()) // c++11
// 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>
classfmt
::
basic_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 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 >, fmt::detail::compile_parse_context< Char, ErrorHandler >
Public Functions
-
constexpr iterator
begin
() const¶ Returns an iterator to the beginning of the format string range being parsed.
-
constexpr 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.
-
constexpr iterator
Output Iterator Support¶
-
template<typename
OutputIt
, typenameS
, typename ...Args
, boolenable
= detail::is_output_iterator<OutputIt, char_t<S>>::value>
autofmt
::
format_to
(OutputIt out, const S &format_str, Args&&... args) -> typename std::enable_if<enable, OutputIt>::type 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, size_t n, const S&, const Args&... args)
-
template<typename
OutputIt
>
structfmt
::
format_to_n_result
¶
Literal-based API¶
The following user-defined literals are defined in fmt/format.h
.
-
detail::udl_formatter<char>
fmt
::
operator""_format
(const char *s, size_t n)¶ User-defined literal equivalent of
fmt::format()
.Example:
using namespace fmt::literals; std::string message = "The answer is {}"_format(42);
-
detail::udl_arg<char>
fmt
::
operator""_a
(const char *s, size_t)¶ 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 detail::char_t_impl<S>::type¶ String’s character type.
-
template<typename
T
>
const void *fmt
::
ptr
(const T *p)¶ Converts
p
toconst void*
for pointer formatting.Example:
auto s = fmt::format("{}", fmt::ptr(p));
-
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<detail::iterator_t<Range>, detail::sentinel_t<Range>, char>fmt
::
join
(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
, typenameSentinel
>
arg_join<It, Sentinel, char>fmt
::
join
(It begin, Sentinel end, string_view sep)¶ Returns an object that formats the iterator range
[begin, end)
with elements separated bysep
.
-
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< char >, 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 >
-
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 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.
-
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) final¶ 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
(detail::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. 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¶
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}.", fmt::localtime(t));
The format string syntax is described in the documentation of strftime.
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.
-
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);
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<detail::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<detail::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);
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.The
'L'
format specifier cannot be combined with presentation specifiers yet.Width calculation doesn’t use grapheme clusterization. The latter has been implemented in a separate branch but hasn’t been integrated yet.
Chrono formatting doesn’t support C++20 date types since they are not provided by standard library implementations.