API Reference¶
All functions and classes provided by the fmt library reside
in namespace fmt
and macros have prefix FMT_
. For brevity the
namespace is usually omitted in examples.
Format API¶
The following functions defined in fmt/format.h
use format string
syntax similar to the one used by Python’s str.format function.
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.
args is an argument list representing arbitrary arguments.
The performance of the format API is close
to that of glibc’s printf
and better than the performance of IOStreams.
For even better speed use the write API.
-
std::string
fmt::
format
(CStringRef format_str, ArgList args)¶ Formats arguments and returns the result as a string.
Example:
std::string message = format("The answer is {}", 42);
Warning
doxygenfunction: Cannot find function “operator”“_format” in doxygen xml output for project “format” from directory: /usr/src/packages/BUILD/obj-i686-linux-gnu/doc/doxyxml
-
void
fmt::
print
(CStringRef format_str, ArgList args)¶ Prints formatted data to
stdout
.Example:
print("Elapsed time: {0:.2f} seconds", 1.23);
-
void
fmt::
print
(std::FILE *f, CStringRef format_str, ArgList args)¶ Prints formatted data to the file f.
Example:
print(stderr, "Don't {}!", "panic");
- template <typename CharType, typename ArgFormatter>
-
class
fmt::
BasicFormatter
¶ This template formats data and writes the output to a writer.
Inherits from fmt::internal::FormatterBase
Public Types
-
typedef CharType
Char
¶ The character type for the output.
Public Functions
-
BasicFormatter
(const ArgList &args, BasicWriter<Char> &w)¶ Constructs a
BasicFormatter
object. References to the arguments and the writer are stored in the formatter object so make sure they have appropriate lifetimes.
-
BasicWriter<Char> &
writer
()¶ Returns a reference to the writer associated with this formatter.
-
void
format
(BasicCStringRef<Char> format_str)¶ Formats stored arguments and writes the output to the writer.
-
typedef CharType
Date and time formatting¶
The library supports strftime-like date and time formatting:
#include "fmt/time.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.
Formatting user-defined types¶
A custom format_arg
function may be implemented and used to format any
user-defined type. That is how date and time formatting described in the
previous section is implemented in fmt/time.h
. The following example
shows how to implement custom formatting for a user-defined structure.
struct MyStruct { double a, b; };
void format_arg(fmt::BasicFormatter<char> &f,
const char *&format_str, const MyStruct &s) {
f.writer().write("[MyStruct: a={:.1f}, b={:.2f}]", s.a, s.b);
}
MyStruct m = { 1, 2 };
std::string s = fmt::format("m={}", n);
// s == "m=[MyStruct: a=1.0, b=2.00]"
Note in the example above the format_arg
function ignores the contents of
format_str
so the type will always be formatted as specified. See
format_arg
in fmt/time.h
for an advanced example of how to use
the format_str
argument to customize the formatted output.
This technique can also be used for formatting class hierarchies:
namespace local {
struct Parent {
Parent(int p) : p(p) {}
virtual void write(fmt::Writer &w) const {
w.write("Parent : p={}", p);
}
int p;
};
struct Child : Parent {
Child(int c, int p) : Parent(p), c(c) {}
virtual void write(fmt::Writer &w) const {
w.write("Child c={} : ", c);
Parent::write(w);
}
int c;
};
void format_arg(fmt::BasicFormatter<char> &f,
const char *&format_str, const Parent &p) {
p.write(f.writer());
}
}
Local::Child c(1,2);
Local::Parent &p = c;
fmt::print("via ref to base: {}\n", p);
fmt::print("direct to child: {}\n", c);
This section shows how to define a custom format function for a user-defined
type. The next section describes how to get fmt
to use a conventional stream
output operator<<
when one is defined for a user-defined type.
std::ostream
support¶
The header 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"
Argument formatters¶
It is possible to change the way arguments are formatted by providing a custom argument formatter class:
// A custom argument formatter that formats negative integers as unsigned
// with the ``x`` format specifier.
class CustomArgFormatter :
public fmt::BasicArgFormatter<CustomArgFormatter, char> {
public:
CustomArgFormatter(fmt::BasicFormatter<char, CustomArgFormatter> &f,
fmt::FormatSpec &s, const char *fmt)
: fmt::BasicArgFormatter<CustomArgFormatter, char>(f, s, fmt) {}
void visit_int(int value) {
if (spec().type() == 'x')
visit_uint(value); // convert to unsigned and format
else
fmt::BasicArgFormatter<CustomArgFormatter, char>::visit_int(value);
}
};
std::string custom_format(const char *format_str, fmt::ArgList args) {
fmt::MemoryWriter writer;
// Pass custom argument formatter as a template arg to BasicFormatter.
fmt::BasicFormatter<char, CustomArgFormatter> formatter(args, writer);
formatter.format(format_str);
return writer.str();
}
FMT_VARIADIC(std::string, custom_format, const char *)
std::string s = custom_format("{:x}", -42); // s == "ffffffd6"
- template <typename Impl, typename Result>
-
class
fmt::
ArgVisitor
¶ An argument visitor based on the curiously recurring template pattern.
To use
ArgVisitor
define a subclass that implements some or all of the visit methods with the same signatures as the methods inArgVisitor
, for example,visit_int()
. Pass the subclass as the Impl template parameter. Then callingvisit()
for some argument will dispatch to a visit method specific to the argument type. For example, if the argument type isdouble
then thevisit_double()
method of a subclass will be called. If the subclass doesn’t contain a method with this signature, then a corresponding method ofArgVisitor
will be called.Example:
class MyArgVisitor : public fmt::ArgVisitor<MyArgVisitor, void> { public: void visit_int(int value) { fmt::print("{}", value); } void visit_double(double value) { fmt::print("{}", value ); } };
Public Functions
-
Result
visit_int
(int value)¶ Visits an
int
argument.
-
Result
visit_long_long
(LongLong value)¶ Visits a
long long
argument.
-
Result
visit_uint
(unsigned value)¶ Visits an
unsigned
argument.
-
Result
visit_ulong_long
(ULongLong value)¶ Visits an
unsigned long long
argument.
-
Result
visit_bool
(bool value)¶ Visits a
bool
argument.
-
Result
visit_char
(int value)¶ Visits a
char
orwchar_t
argument.
- template <typename T>
-
Result
visit_any_int
(T)¶ Visits an argument of any integral type.
-
Result
visit_double
(double value)¶ Visits a
double
argument.
-
Result
visit_long_double
(long double value)¶ Visits a
long double
argument.
- template <typename T>
-
Result
visit_any_double
(T)¶ Visits a
double
orlong double
argument.
-
Result
visit_cstring
(const char *)¶ Visits a null-terminated C string (
const char *
) argument.
-
Result
visit_string
(Arg::StringValue<char>)¶ Visits a string argument.
-
Result
visit_wstring
(Arg::StringValue<wchar_t>)¶ Visits a wide string argument.
-
Result
visit_pointer
(const void *)¶ Visits a pointer argument.
-
Result
visit_custom
(Arg::CustomValue)¶ Visits an argument of a custom (user-defined) type.
-
Result
visit
(const Arg &arg)¶ Visits an argument dispatching to the appropriate visit method based on the argument type. For example, if the argument type is
double
then thevisit_double()
method of the Impl class will be called.
-
Result
- template <typename Impl, typename Char, typename Spec = fmt::FormatSpec>
-
class
fmt::
BasicArgFormatter
¶ An argument formatter based on the curiously recurring template pattern.
To use
BasicArgFormatter
define a subclass that implements some or all of the visit methods with the same signatures as the methods inArgVisitor
, for example,visit_int()
. Pass the subclass as the Impl template parameter. When a formatting function processes an argument, it will dispatch to a visit method specific to the argument type. For example, if the argument type isdouble
then thevisit_double()
method of a subclass will be called. If the subclass doesn’t contain a method with this signature, then a corresponding method ofBasicArgFormatter
or its superclass will be called.Inherits from fmt::internal::ArgFormatterBase< Impl, Char, Spec >
Public Functions
-
BasicArgFormatter
(BasicFormatter<Char, Impl> &formatter, Spec &spec, const Char *fmt)¶ Constructs an argument formatter object. formatter is a reference to the main formatter object, spec contains format specifier information for standard argument types, and fmt points to the part of the format string being parsed for custom argument types.
-
void
visit_custom
(internal::Arg::CustomValue c)¶ Formats an argument of a custom (user-defined) type.
-
- template <typename Char>
-
class
fmt::
ArgFormatter
¶ The default argument formatter.
Inherits from fmt::BasicArgFormatter< ArgFormatter< Char >, Char, FormatSpec >
Public Functions
-
ArgFormatter
(BasicFormatter<Char> &formatter, FormatSpec &spec, const Char *fmt)¶ Constructs an argument formatter object.
-
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.
-
int
fmt::
printf
(CStringRef format, ArgList args)¶ Prints formatted data to
stdout
.Example:
fmt::printf("Elapsed time: %.2f seconds", 1.23);
-
int
fmt::
fprintf
(std::FILE *f, CStringRef format, ArgList args)¶ Prints formatted data to the file f.
Example:
fmt::fprintf(stderr, "Don't %s!", "panic");
-
int
fmt::
fprintf
(std::ostream &os, CStringRef format_str, ArgList args)¶ Prints formatted data to the stream os.
Example:
fprintf(cerr, "Don't %s!", "panic");
-
std::string
fmt::
sprintf
(CStringRef format, ArgList args)¶ Formats arguments and returns the result as a string.
Example:
std::string message = fmt::sprintf("The answer is %d", 42);
- template <typename Char, typename ArgFormatter = PrintfArgFormatter<Char>>
-
class
fmt::
PrintfFormatter
¶ This template formats data and writes the output to a writer.
Inherits from fmt::internal::FormatterBase
Public Functions
-
PrintfFormatter
(const ArgList &al, BasicWriter<Char> &w)¶ Constructs a
PrintfFormatter
object. References to the arguments and the writer are stored in the formatter object so make sure they have appropriate lifetimes.
-
void
format
(BasicCStringRef<Char> format_str)¶ Formats stored arguments and writes the output to the writer.
-
- template <typename Impl, typename Char, typename Spec>
-
class
fmt::
BasicPrintfArgFormatter
¶ A
printf
argument formatter based on the curiously recurring template pattern.To use
BasicPrintfArgFormatter
define a subclass that implements some or all of the visit methods with the same signatures as the methods inArgVisitor
, for example,visit_int()
. Pass the subclass as the Impl template parameter. When a formatting function processes an argument, it will dispatch to a visit method specific to the argument type. For example, if the argument type isdouble
then thevisit_double()
method of a subclass will be called. If the subclass doesn’t contain a method with this signature, then a corresponding method ofBasicPrintfArgFormatter
or its superclass will be called.Inherits from fmt::internal::ArgFormatterBase< Impl, Char, Spec >
Public Functions
-
BasicPrintfArgFormatter
(BasicWriter<Char> &w, Spec &s)¶ Constructs an argument formatter object. writer is a reference to the output writer and spec contains format specifier information for standard argument types.
-
void
visit_bool
(bool value)¶ Formats an argument of type
bool
.
-
void
visit_char
(int value)¶ Formats a character.
-
void
visit_cstring
(const char *value)¶ Formats a null-terminated C string.
-
void
visit_pointer
(const void *value)¶ Formats a pointer.
-
void
visit_custom
(internal::Arg::CustomValue c)¶ Formats an argument of a custom (user-defined) type.
-
- template <typename Char>
-
class
fmt::
PrintfArgFormatter
¶ The default printf argument formatter.
Inherits from fmt::BasicPrintfArgFormatter< PrintfArgFormatter< Char >, Char, FormatSpec >
Public Functions
-
PrintfArgFormatter
(BasicWriter<Char> &w, FormatSpec &s)¶ Constructs an argument formatter object.
-
Write API¶
The write API provides classes for writing formatted data into character
streams. It is usually faster than the format API but, as IOStreams,
may result in larger compiled code size. The main writer class is
BasicMemoryWriter
which stores its output in a memory buffer and
provides direct access to it. It is possible to create custom writers that
store output elsewhere by subclassing BasicWriter
.
- template <typename Char>
-
class
fmt::
BasicWriter
¶ This template provides operations for formatting and writing data into a character stream. The output is stored in a buffer provided by a subclass such as
fmt::BasicMemoryWriter
.You can use one of the following typedefs for common character types:
Type Definition Writer BasicWriter<char> WWriter BasicWriter<wchar_t> Subclassed by fmt::BasicArrayWriter< Char >, fmt::BasicMemoryWriter< Char, Allocator >, fmt::BasicStringWriter< Char, Allocator >
Public Functions
-
virtual
~BasicWriter
()¶ Destroys a
BasicWriter
object.
-
std::size_t
size
() const¶ Returns the total number of characters written.
-
const Char *
data
() const¶ Returns a pointer to the output buffer content.
No terminating null character is appended.
-
const Char *
c_str
() const¶ Returns a pointer to the output buffer content with terminating null character appended.
-
std::basic_string<Char>
str
() const¶ Returns the content of the output buffer as an
std::string
.
-
void
write
(BasicCStringRef<Char> format, ArgList args)¶ Writes formatted data.
args is an argument list representing arbitrary arguments.
Example:
MemoryWriter out; out.write("Current point:\n"); out.write("({:+f}, {:+f})", -3.14, 3.14);
This will write the following output to the
out
object:Current point: (-3.140000, +3.140000)
The output can be accessed using
data()
,c_str()
orstr()
methods.See also Format String Syntax.
-
BasicWriter &
operator<<
(ULongLong value)¶ Formats value and writes it to the stream.
-
BasicWriter &
operator<<
(long double value)¶ Formats value using the general format for floating-point numbers (
'g'
) and writes it to the stream.
-
BasicWriter &
operator<<
(char value)¶ Writes a character to the stream.
-
BasicWriter &
operator<<
(fmt::BasicStringRef<Char> value)¶ Writes value to the stream.
-
virtual
- template <typename Char, typename Allocator = std::allocator<Char>>
-
class
fmt::
BasicMemoryWriter
¶ This class template provides operations for formatting and writing data into a character stream. The output is stored in a memory buffer that grows dynamically.
You can use one of the following typedefs for common character types and the standard allocator:
Type Definition MemoryWriter BasicMemoryWriter<char, std::allocator<char>> WMemoryWriter BasicMemoryWriter<wchar_t, std::allocator<wchar_t>> Example:
MemoryWriter out; out << "The answer is " << 42 << "\n"; out.write("({:+f}, {:+f})", -3.14, 3.14);
This will write the following output to the
out
object:The answer is 42 (-3.140000, +3.140000)
The output can be converted to an
std::string
without.str()
or accessed as a C string without.c_str()
.Inherits from fmt::BasicWriter< Char >
Public Functions
-
BasicMemoryWriter
(BasicMemoryWriter &&other)¶ Constructs a
fmt::BasicMemoryWriter
object moving the content of the other object to it.
-
BasicMemoryWriter &
operator=
(BasicMemoryWriter &&other)¶ Moves the content of the other
BasicMemoryWriter
object to this one.
-
- template <typename Char>
-
class
fmt::
BasicArrayWriter
¶ This class template provides operations for formatting and writing data into a fixed-size array. For writing into a dynamically growing buffer use
fmt::BasicMemoryWriter
.Any write method will throw
std::runtime_error
if the output doesn’t fit into the array.You can use one of the following typedefs for common character types:
Type Definition ArrayWriter BasicArrayWriter<char> WArrayWriter BasicArrayWriter<wchar_t> Inherits from fmt::BasicWriter< Char >
Public Functions
-
BasicArrayWriter
(Char *array, std::size_t size)¶ Constructs a
fmt::BasicArrayWriter
object for array of the given size.
- template <std::size_t SIZE>
-
BasicArrayWriter
(Char (&array)[SIZE])¶ Constructs a
fmt::BasicArrayWriter
object for array of the size known at compile time.
-
- template <typename Char, typename Allocator = std::allocator<Char>>
-
class
fmt::
BasicStringWriter
¶ This class template provides operations for formatting and writing data into a character stream. The output is stored in a
std::basic_string
that grows dynamically.You can use one of the following typedefs for common character types and the standard allocator:
Type Definition StringWriter BasicStringWriter<char> WStringWriter BasicStringWriter<wchar_t> Example:
StringWriter out; out << "The answer is " << 42 << "\n";
This will write the following output to the
out
object:The answer is 42
The output can be moved to a
std::basic_string
without.move_to()
.Inherits from fmt::BasicWriter< Char >
Public Functions
-
BasicStringWriter
(const Allocator &allocator = Allocator())¶ Constructs a
fmt::BasicStringWriter
object.
-
void
move_to
(std::basic_string<Char, std::char_traits<Char>, Allocator> &str)¶ Moves the buffer content to str clearing the buffer.
-
- template <class Container>
-
class
fmt::
BasicContainerWriter
¶ This class template provides operations for formatting and appending data to a standard container like
std::vector
orstd::basic_string
.Example:
void vecformat(std::vector<char>& dest, fmt::BasicCStringRef<char> format, fmt::ArgList args) { fmt::BasicContainerWriter<std::vector<char> > appender(dest); appender.write(format, args); } FMT_VARIADIC(void, vecformat, std::vector<char>&, fmt::BasicCStringRef<char>);
Inherits from fmt::BasicWriter< Container::value_type >
Public Functions
-
BasicContainerWriter
(Container &dest)¶ Constructs a
fmt::BasicContainerWriter
object.
-
-
IntFormatSpec<int, TypeSpec<'b'>>
fmt::
bin
(int value)¶ Returns an integer format specifier to format the value in base 2.
-
IntFormatSpec<int, TypeSpec<'o'>>
fmt::
oct
(int value)¶ Returns an integer format specifier to format the value in base 8.
-
IntFormatSpec<int, TypeSpec<'x'>>
fmt::
hex
(int value)¶ Returns an integer format specifier to format the value in base 16 using lower-case letters for the digits above 9.
-
IntFormatSpec<int, TypeSpec<'X'>>
fmt::
hexu
(int value)¶ Returns an integer formatter format specifier to format in base 16 using upper-case letters for the digits above 9.
- template <char TYPE_CODE, typename Char>
-
IntFormatSpec<int, AlignTypeSpec<TYPE_CODE>, Char>
fmt::
pad
(int value, unsigned width, Char fill = ' ')¶ Returns an integer format specifier to pad the formatted argument with the fill character to the specified width using the default (right) numeric alignment.
Example:
MemoryWriter out; out << pad(hex(0xcafe), 8, '0'); // out.str() == "0000cafe"
Utilities¶
- template <typename T>
-
internal::NamedArgWithType<char, T>
fmt::
arg
(StringRef name, const T &arg)¶ Returns a named argument for formatting functions.
Example:
print("Elapsed time: {s:.2f} seconds", arg("s", 1.23));
Warning
doxygenfunction: Cannot find function “operator”“_a” in doxygen xml output for project “format” from directory: /usr/src/packages/BUILD/obj-i686-linux-gnu/doc/doxyxml
-
FMT_CAPTURE
(...)¶ Convenient macro to capture the arguments’ names and values into several
fmt::arg(name, value)
.Example:
int x = 1, y = 2; print("point: ({x}, {y})", FMT_CAPTURE(x, y)); // same as: // print("point: ({x}, {y})", arg("x", x), arg("y", y));
-
FMT_VARIADIC
(ReturnType, func, ...)¶ Defines a variadic function with the specified return type, function name and argument types passed as variable arguments to this macro.
Example:
void print_error(const char *file, int line, const char *format, fmt::ArgList args) { fmt::print("{}: {}: ", file, line); fmt::print(format, args); } FMT_VARIADIC(void, print_error, const char *, int, const char *)
FMT_VARIADIC
is used for compatibility with legacy C++ compilers that don’t implement variadic templates. You don’t have to use this macro if you don’t need legacy compiler support and can use variadic templates directly:template <typename... Args> void print_error(const char *file, int line, const char *format, const Args & ... args) { fmt::print("{}: {}: ", file, line); fmt::print(format, args...); }
-
class
fmt::
ArgList
¶ An argument list.
Public Functions
-
internal::Arg
operator[]
(unsigned index) const¶ Returns the argument at specified index.
-
internal::Arg
- template <typename T>
-
std::string
fmt::
to_string
(const T &value)¶ Converts value to
std::string
using the default format for type T.Example:
#include "fmt/string.h" std::string answer = fmt::to_string(42);
- template <typename T>
-
std::wstring
fmt::
to_wstring
(const T &value)¶ Converts value to
std::wstring
using the default format for type T.Example:
#include "fmt/string.h" std::wstring answer = fmt::to_wstring(42);
- template <typename Char>
-
class
fmt::
BasicStringRef
¶ A string reference. It can be constructed from a C string or
std::basic_string
.You can use one of the following typedefs for common character types:
Type Definition StringRef BasicStringRef<char> WStringRef BasicStringRef<wchar_t> This class is most useful as a parameter type to allow passing different types of strings to a function, for example:
template <typename... Args> std::string format(StringRef format_str, const Args & ... args); format("{}", 42); format(std::string("{}"), 42);
Public Functions
-
BasicStringRef
(const Char *s, std::size_t size)¶ Constructs a string reference object from a C string and a size.
-
BasicStringRef
(const Char *s)¶ Constructs a string reference object from a C string computing the size with
std::char_traits<Char>::length
.
- template <typename Allocator>
-
BasicStringRef
(const std::basic_string<Char, std::char_traits<Char>, Allocator> &s)¶ Constructs a string reference from a
std::basic_string
object.
-
std::basic_string<Char>
to_string
() const¶ Converts a string reference to an
std::string
object.
-
const Char *
data
() const¶ Returns a pointer to the string data.
-
std::size_t
size
() const¶ Returns the string size.
-
- template <typename Char>
-
class
fmt::
BasicCStringRef
¶ A reference to a null terminated string. It can be constructed from a C string or
std::basic_string
.You can use one of the following typedefs for common character types:
Type Definition CStringRef BasicCStringRef<char> WCStringRef BasicCStringRef<wchar_t> This class is most useful as a parameter type to allow passing different types of strings to a function, for example:
template <typename... Args> std::string format(CStringRef format_str, const Args & ... args); format("{}", 42); format(std::string("{}"), 42);
Public Functions
-
BasicCStringRef
(const Char *s)¶ Constructs a string reference object from a C string.
- template <typename Allocator>
-
BasicCStringRef
(const std::basic_string<Char, std::char_traits<Char>, Allocator> &s)¶ Constructs a string reference from a
std::basic_string
object.
-
const Char *
c_str
() const¶ Returns the pointer to a C string.
-
- template <typename T>
-
class
fmt::
Buffer
¶ A buffer supporting a subset of
std::vector
‘s operations.Subclassed by fmt::internal::MemoryBuffer< T, SIZE, Allocator >
Public Functions
-
std::size_t
size
() const¶ Returns the size of this buffer.
-
std::size_t
capacity
() const¶ Returns the capacity of this buffer.
-
void
resize
(std::size_t new_size)¶ Resizes the buffer.
If T is a POD type new elements may not be initialized.
-
void
reserve
(std::size_t capacity)¶ Reserves space to store at least capacity elements.
- template <typename U>
-
void
append
(const U *begin, const U *end)¶ Appends data to the end of the buffer.
Protected Functions
-
virtual void
grow
(std::size_t size) = 0¶ Increases the buffer capacity to hold at least size elements updating
ptr_
andcapacity_
.
-
std::size_t
System errors¶
-
class
fmt::
SystemError
¶ An error returned by an operating system or a language runtime, for example a file opening error.
Inherits from fmt::internal::RuntimeError
Subclassed by fmt::WindowsError
Public Functions
-
SystemError
(int error_code, CStringRef message)¶ Constructs a
fmt::SystemError
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 SystemError 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::SystemError(errno, "cannot open file '{}'", filename);
-
-
void
fmt::
format_system_error
(fmt::Writer &out, int error_code, fmt::StringRef 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::
WindowsError
¶ A Windows error.
Inherits from fmt::SystemError
Public Functions
-
WindowsError
(int error_code, CStringRef message)¶ Constructs a
fmt::WindowsError
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 WindowsError 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::WindowsError(GetLastError(), "cannot open file '{}'", filename); }
-
Custom allocators¶
The fmt library supports custom dynamic memory allocators.
A custom allocator class can be specified as a template argument to
fmt::BasicMemoryWriter
:
typedef fmt::BasicMemoryWriter<char, CustomAllocator> CustomMemoryWriter;
It is also possible to write a formatting function that uses a custom allocator:
typedef std::basic_string<char, std::char_traits<char>, CustomAllocator>
CustomString;
CustomString format(CustomAllocator alloc, fmt::CStringRef format_str,
fmt::ArgList args) {
CustomMemoryWriter writer(alloc);
writer.write(format_str, args);
return CustomString(writer.data(), writer.size(), alloc);
}
FMT_VARIADIC(CustomString, format, CustomAllocator, fmt::CStringRef)