d4c6fa3122
cd4af11ef Update version 1ebc2f7cc Bump version f4c997062 Fix changelog 72920ba30 Update changelog 0907c08ae Fix handling of default alignmment with locale (#1801) 37c8f4eaf Don't use 128 bit integers with clang-cl (#1800) eaaaec999 Workaround a bug in msvc ccf8561cb Workaround broken numeric_limites, part 2 (#1787) 0cc73ebf7 Report error on missing named argument (#1796) 33efc3c94 Fix handling of iterators in locale-specific formatting (#1782) b9d749095 Update version 86b63bb71 Bump version cbf6be960 Update changelog 229ee9b46 Workaround broken numeric_limits (#1725) 2b7a146fa Fix a regression in handling digit separators (#1782) 89d0c7124 Fix compatibility with CMake 3.4 (#1779) f19b1a521 Update version 5c67fefb2 Fix a changelog entry 1d2a556e1 Fix undefined reference error 04c9b62fb Merge release branch 6be6762e5 Fix date f1dd2eb3c Bump version fbf3b943c Workaround a bug in gcc a29a01d30 Fix docs 9f0b3afb7 Bump version in namespace 86b2f99f8 Fix the docs c472ff12d Update version 5173a76ba Update version 1614af352 Minor corrections in the changelog 569a9b3a7 Bump version 4e7e3c65a Update docs 0f7a6bfa1 Add a section on std::format compatibility 4faec5a5e Update README.rst 7dbc8ac71 Update changelog c87dd746f Update changelog 372175caf Revert changelog changes 904754876 Add ClickHouse to the list of projects (#1751) d30bca64e Revert changelog conversion since GFM is not supported there d6047cdc4 Update changelog 810241b36 Convert changlog to markdown 661c47473 Rename changelog 7c33059fa Update ChangeLog.rst 9e20883ab Update README.rst 41899d522 Update changelog f42f45908 Update changelog 2381df654 Update readme 7ae816563 Update README.rst c56cf3d07 Update changelog and readme 01309a34a Deprecate arg_formatter a62d06055 Update changelog 23e3a2eee Update changelog d8e0554b9 Disable numeric formatting by default 1e8eea4f4 Update changelog 44bd5384a Fix formatting 20e19387a Update changelog 56fed7814 FMT_NUMERIC_ALIGN -> FMT_DEPRECATED_NUMERIC_ALIGN 56e63078f Make the n specifier an opt-in 31ce6bc70 Fix a conversion warning with Clang10 on Windows (#1750) c9c5b90da Fix a typo. Thanks Tracy Chapman from TripleChecker 1f3f84631 Fix a typo 5de62af60 Fix possible infinite recursion in FMT_ASSERT (#1744) cbddab2fe Use consistent include style f69b6eaab Add a simple buffered stream with no sync ba363b3a2 Use digit pairs as in unrolledlut a6f8e7d86 Update changelog e753244ab Update changelog 98a7a8b40 Update changelog and disable internal 3135d95fd Don't use non-portable attribute 8630a8f5f Tweak the docs cc3a88e6b Extract docs from compile.h 79c4b6bd7 Apply clang-format d130ee070 Document format string compilation d0f90b5be Spelling fixes 6e080660d Update README.rst 31c3a2426 Spelling fixes 613b3b459 Spelling fixes 978521bb8 Fix a compile error introduced in #1738 4e94c649f Deprecate compile 1a83443e6 Add user-defined type support to compilation 8bef1c3b3 Tweaks for EDG based compilers (Intel, nVidia, MCST/Elbrus, etc). b287c37c6 Do not use -Wl,--as-needed with emscripten. 2cac8a9d2 Reintroduce UDT support to fmt::to_string and test ADL 9a4cc8842 Add FMT_COMPILE support to format_to 5ddf9ee1b Streamline default FP formatting 0b3a83f7f Update README.rst 5aa5c9873 Added #define WIN32_LEAN_AND_MEAN before including windows.h (#1729) 397ad1bec Optimize common case 7431165f3 Make to_string bypass format ee4d4c7fd Inline compiled format ab2f8484e Finish text::format e900d735b Re-enable assert in format_decimal f4de7b684 Fix ambiguity 1f8f5450b Reuse format_decimal d702a68df Fix formatting of bool with FMT_COMPILE and add more tests e956a14e9 Use write instead of format_int in to_string 98dcc251e Undo branching reduction 5b8641ddd Undo branching reduction 8c88abde6 Fix sign handling in 'L' 23b976a61 Reduce branching 9edee0e72 Optimize small string parsing a909d42b7 Fix a warning 16637341b Enable compilation for all types 2d71d7e03 Add a simple format string compilation API d259fcfb0 Tweak comments 704ed557a Move project in order to solve a CMake warning 8603bd20d Update README.rst 547f12ae6 Fix a warning (#1722) f904e8a1b c++11 use formatting user-defined types (#1721) 100e8af08 Update README.rst c11d0f056 Update README.rst 2453ee576 Improve default formatting 47ae52155 MINGW cross compiler fixes 936a1833c Add default_arg_formatter f2c9cb624 Fix a UB d3107f855 Cleanup arg_formatter_base 5e7c70e20 Simplify arg_formatter_base 38cc68b3e Inline visitor 6732ea500 Make symbols readable 57ddc77ce Make advance_to a noop for back_insert_iterator 50bad7d62 Optimize format string parsing 8f7a824e4 Inline visit f11e96870 Optimize format string parsing 09737dd83 Optimize format handler d9e3d6e6e Move format_handler to detail 795b47a7b Fix a warning (#1712) 95c6ac0cc fix typo which caused the loss of the counting information when using a printf context with a truncating_iterator 21409cfdd Fix warnings 88c8d534e Move digits10 to where they belong and add comments 0f3eaeac0 Fix a warning 344218510 Ignore /doc/node_modules directory 16aec0617 Cleanup arg_formatter_base 1e1193590 Fix format_decimal overloads 0893c9c2e Inline parse_format_string 3245145a4 Remove undocumented buffer_range and output_range 57fc44907 Increase VM disk size 7d22bebb6 Remove uses of buffer_range 8f2b5fe74 Don't install sphinx cache files f095c67b6 Remove uses of buffer_range 5aabf1f71 Simplify copy_str 19c5b5d15 Simplify arg_formatter 519571ede Simplify arg_formatter_base ac8dfd841 Improve handling of separators 2c6165a22 Reduce the number of comparisons 28639969e Use memcpy for copying digits f5fa1dee5 Support custom FMT_INC_DIR in pkgconfig and cmake configs (#1702) 51bf9cfac Fix Mingw support 1a716caf5 Optimize common case 98d4bbf81 Update README.rst 8c8f74a87 fix zero flag for char types and make zero flag ignored if a precision is specified bc1b89da2 Temporarily revert parsing changes a7fb321ac Remove a redundant branch 8cadb9650 fix max/min macro (#1697) 297c3b2ed Fix an example (thanks Alexey Kuzmenko) 943532fec Make ostream formatter work with compile-time format strings (#1692) bd8804019 Update README.rst f230300ac Knuth is using fmt library (#1691) a265e25b7 Optimize small string parsing 2aa2526f6 Optimize small string concatenation 8d78045e7 Move void_t to where it's used 7aafa6bc6 Update analytics c66aae165 Adding sentinel support to fmt::join(). (#1689) 6d66de380 Add c specifier support to integral types (#1652) 6b219a58d fix interaction of space flag and '+' flag, as well as '-' flag and '0' flag (#1687) eee2023c2 Update signatures c5ed73aab Add fmt::detail::buffer to the docs (#704) ea1cd9638 Fix apidoc d3964d7b1 Merge branch 'master' of github.com:fmtlib/fmt d18c6723a Update docs 96c18b26c make plus flag for printf not be ignored for char argument (#1683) ba25baeb9 Apply doc patch to 6.2.1 981b517cc nested replacement fields may omit arg_id (#1681) 922ea924b Make dynamic_format_arg_store reusable and add reserve() (#1677) e0d98923c Update version 806926537 internal -> detail (#1538) 963ee0831 Simplify named arguments 02a6fe59f Named arguments go brrr de290f5c4 Ditch internal::arg_map d0623de51 Bump version 73e335ed3 Make implicit capture explicit for C++20 (#1669) b4d46e398 Update changelog a182f7341 Update changelog 68201831a Support named args in dynamic_format_arg_store (#1655). (#1663) 7f723fbcb Consistently namespace qualify size_t c06851456 Purge basic_writer 2f05054dd Purge basic_writer f0ce21164 Revert enum change 44639b11f Fix some warnings (#1667) 1c86a99e8 Purge basic_writer 8f511fc12 Make copyfmt not throw (#1666) 59fe455f3 Remove compatibility stubs b0f47a13e Separate nonfinite formatting d6cea50d0 Remove deprecated APIs 40bc7163f Move FMT_MAYBE_UNUSED to where it's actually used 080e44d0b Fix inconsistent type detection (#1662) 7e57cace5 Exclude std::abort from compilation when compiling CUDA with Clang (#1661) 7b66e2f21 Inherit arg_formatter_base from basic_writer bab3f5800 Refactor pointer formatting 9cc7edfdd Move int_writer to the namespace scope 8d9d528bf Improve handling of alignment 8efd1a8ef Improve handling of alignment a71bc9c82 Use '0' fill with numeric align for consistency with std::format 60d85d598 Suppress ubsan warning c3099beb6 Cleanup cbb4cb899 Remove undocumented deprecated APIs b85e9ac38 Simplify vformat_to e3710ab97 FMT_CONSTEXPR -> constexpr d59751f0f Update date formatting example to use threadsafe localtime d6abb2fa0 Reduce library size e9fdea90b Update README.rst 44b6584f2 Update README.rst 78f041ab5 build: Fix installation paths 7ca89bf87 Reduce template bloat in write_int 3c114d091 Fix a shadowing warning (#1658) e2ef12a8c Allow to avoid inclusion of os.cc in fmt target bca82719a Pass iterator by value 99da38962 Make write_padded non-members f19d66794 Bump fuzzer allocation limit 3e6984761 Reduce branching in write_padded 9ac1eebd4 Reduce library size e2ff91067 Replace FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION with fmt-specific macro (#1650) f2ed03b91 Fix a warning (#1649) 9dde9f013 Reduce library size b1af642d1 Reduce library size 4a617f25c Clarify encoding conversion in chrono 6f435f55c Improve compile time by using extern template (#1452) cb475cb88 Clarify why we don't check argument id 1e1ac6e96 Check dynamic width/precision id at compile time (#1614) e51c449fe Revert "Check dynamic widht/precision id at compile time (#1614)" 0463665ef Don't access a C string past precision in printf (#1595) 7d748a6f8 Check dynamic widht/precision id at compile time (#1614) 2b75bd7ce Get rid of do_check_format_string 4a1d5931c Simplify udl_formatter with FMT_STRING 811b0f905 Enable compile-time error tests 450e8eed9 Fix markup b8fbcec1b Clarify formatter reuse 56bc86ffa Suppress bogus MSVC analysis warnings 3f79357ef Fix a recent regression in handling max packed arguments 8a11148f9 Add Facebook Folly to the list of projects e371e8b68 Tweak readme 813732fed Improve readme formatting 3670d5b3f README: add vectorized.io/redpanda in the list of users 9e2ad7cf6 Add windows terminal to the projects using {fmt} 63479c851 Use a delegating ctor and add inlines 5944fcad3 Remove remaining wchar_t instantiation e253b371b Don't generate RTTI for allocator 0c86f467b Fix build on ancient gcc 1929df4bc Simplify format_args a13822181 Always inline arg_data functions 04e0dfd4b Always inline value ctors 04cde756b Simplify checks c9a57b9a8 Fix incorrect assumptions about nul termination f46f5ecaf Reenable constexpr _compile on GCC 9 6e8d7e277 Don't use constexpr on Intel compiler (#1628) 567ed03f8 Merge arg overloads and cleanup c3fa33314 Remove warning in core.h with when compiling with gcc and -Wshadow 84898b462 Remove warning in format.h when compiling with gcc and -Wshadow 538d83fd0 Cleanup named arguments 8a4630686 Improve handling of named arguments a9d62d3f3 Add check for CompiledFormat to avoid ambiguous call fdcf7870a Add stack-based named argument storage 5899267c4 Fix a clang-tidy warning 07b4c246e Fix a typo e99809f29 Fix ostream support in sprintf (#1631) 3cd5179f3 Fixed clang tidy warning -multiple declarations in a single statement reduces readability 7404e33a7 Fix clang warning about explicit ctor 3aab2171e Clean up basic_format_args 7645ca072 Clean up printf e30d8391e Suppress an MSVC warning (#1622) 8cd8ef03e Simplify warning suppression bbb6b357c Add floating-point L specifier (#1624) 36ea32640 Suppress a bogus MSVC warning 141a00d64 Define FMT_EXTERN_TEMPLATE_API on export 3860edc5d Bump version 7d01859ef Fix handling of unsigned char strings in printf 63b23e786 Merge branch 'master' of github.com:fmtlib/fmt 4999796c1 Fix the docs 34b3f7b7a Avoid windows issue with min() max() macros 27e3c0fe9 Update signature in the docs git-subtree-dir: externals/fmt git-subtree-split: cd4af11efc9c622896a3e4cb599fa28668ca3d05
455 lines
14 KiB
ReStructuredText
455 lines
14 KiB
ReStructuredText
.. _string-formatting-api:
|
|
|
|
*************
|
|
API Reference
|
|
*************
|
|
|
|
The {fmt} library API consists of the following parts:
|
|
|
|
* :ref:`fmt/core.h <core-api>`: the core API providing argument handling
|
|
facilities and a lightweight subset of formatting functions
|
|
* :ref:`fmt/format.h <format-api>`: the full format API providing compile-time
|
|
format string checks, wide string, output iterator and user-defined type
|
|
support
|
|
* :ref:`fmt/ranges.h <ranges-api>`: additional formatting support for ranges
|
|
and tuples
|
|
* :ref:`fmt/chrono.h <chrono-api>`: date and time formatting
|
|
* :ref:`fmt/compile.h <compile-api>`: format string compilation
|
|
* :ref:`fmt/ostream.h <ostream-api>`: ``std::ostream`` support
|
|
* :ref:`fmt/printf.h <printf-api>`: ``printf`` formatting
|
|
|
|
All functions and types provided by the library reside in namespace ``fmt`` and
|
|
macros have prefix ``FMT_``.
|
|
|
|
.. _core-api:
|
|
|
|
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 :ref:`format string syntax <syntax>`
|
|
similar to that of Python's `str.format
|
|
<http://docs.python.org/3/library/stdtypes.html#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.
|
|
|
|
.. _format:
|
|
|
|
.. doxygenfunction:: format(const S&, Args&&...)
|
|
.. doxygenfunction:: vformat(const S&, basic_format_args<buffer_context<type_identity_t<Char>>>)
|
|
|
|
.. _print:
|
|
|
|
.. doxygenfunction:: print(const S&, Args&&...)
|
|
.. doxygenfunction:: vprint(string_view, format_args)
|
|
|
|
.. doxygenfunction:: print(std::FILE *, const S&, Args&&...)
|
|
.. doxygenfunction:: vprint(std::FILE *, string_view, format_args)
|
|
|
|
Named Arguments
|
|
---------------
|
|
|
|
.. doxygenfunction:: fmt::arg(const S&, const T&)
|
|
|
|
Named arguments are not supported in compile-time checks at the moment.
|
|
|
|
Argument Lists
|
|
--------------
|
|
|
|
.. doxygenfunction:: fmt::make_format_args(const Args&...)
|
|
|
|
.. doxygenclass:: fmt::format_arg_store
|
|
:members:
|
|
|
|
.. doxygenclass:: fmt::dynamic_format_arg_store
|
|
:members:
|
|
|
|
.. doxygenclass:: fmt::basic_format_args
|
|
:members:
|
|
|
|
.. doxygenstruct:: fmt::format_args
|
|
|
|
.. doxygenclass:: fmt::basic_format_arg
|
|
:members:
|
|
|
|
Compatibility
|
|
-------------
|
|
|
|
.. doxygenclass:: fmt::basic_string_view
|
|
:members:
|
|
|
|
.. doxygentypedef:: fmt::string_view
|
|
.. doxygentypedef:: fmt::wstring_view
|
|
|
|
Locale
|
|
------
|
|
|
|
All formatting is locale-independent by default. Use the ``'n'`` format
|
|
specifier to insert the appropriate number separator characters from the
|
|
locale::
|
|
|
|
#include <fmt/core.h>
|
|
#include <locale>
|
|
|
|
std::locale::global(std::locale("en_US.UTF-8"));
|
|
auto s = fmt::format("{:L}", 1000000); // s == "1,000,000"
|
|
|
|
.. _format-api:
|
|
|
|
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 supported for built-in and string types as well as
|
|
user-defined types with ``constexpr`` ``parse`` functions in their ``formatter``
|
|
specializations.
|
|
|
|
.. doxygendefine:: FMT_STRING
|
|
|
|
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
|
|
|
|
.. code-block:: c++
|
|
|
|
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"
|
|
}
|
|
|
|
.. doxygenclass:: fmt::basic_format_parse_context
|
|
:members:
|
|
|
|
Output Iterator Support
|
|
-----------------------
|
|
|
|
.. doxygenfunction:: fmt::format_to(OutputIt, const S&, Args&&...)
|
|
.. doxygenfunction:: fmt::format_to_n(OutputIt, size_t, const S&, const Args&...)
|
|
.. doxygenstruct:: fmt::format_to_n_result
|
|
:members:
|
|
|
|
Literal-based API
|
|
-----------------
|
|
|
|
The following user-defined literals are defined in ``fmt/format.h``.
|
|
|
|
.. doxygenfunction:: operator""_format(const char *, size_t)
|
|
|
|
.. doxygenfunction:: operator""_a(const char *, size_t)
|
|
|
|
Utilities
|
|
---------
|
|
|
|
.. doxygenstruct:: fmt::is_char
|
|
|
|
.. doxygentypedef:: fmt::char_t
|
|
|
|
.. doxygenfunction:: fmt::formatted_size(string_view, const Args&...)
|
|
|
|
.. doxygenfunction:: fmt::to_string(const T&)
|
|
|
|
.. doxygenfunction:: fmt::to_wstring(const T&)
|
|
|
|
.. doxygenfunction:: fmt::to_string_view(const Char *)
|
|
|
|
.. doxygenfunction:: fmt::join(const Range&, string_view)
|
|
|
|
.. doxygenfunction:: fmt::join(It, Sentinel, string_view)
|
|
|
|
.. doxygenclass:: fmt::detail::buffer
|
|
:members:
|
|
|
|
.. doxygenclass:: fmt::basic_memory_buffer
|
|
:protected-members:
|
|
:members:
|
|
|
|
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.
|
|
|
|
.. doxygenclass:: fmt::system_error
|
|
:members:
|
|
|
|
.. doxygenfunction:: fmt::format_system_error
|
|
|
|
.. doxygenclass:: fmt::windows_error
|
|
:members:
|
|
|
|
.. _formatstrings:
|
|
|
|
Custom Allocators
|
|
-----------------
|
|
|
|
The {fmt} library supports custom dynamic memory allocators.
|
|
A custom allocator class can be specified as a template argument to
|
|
:class:`fmt::basic_memory_buffer`::
|
|
|
|
using custom_memory_buffer =
|
|
fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
|
|
|
|
It is also possible to write a formatting function that uses a custom
|
|
allocator::
|
|
|
|
using custom_string =
|
|
std::basic_string<char, std::char_traits<char>, custom_allocator>;
|
|
|
|
custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
|
|
fmt::format_args args) {
|
|
custom_memory_buffer buf(alloc);
|
|
fmt::vformat_to(buf, format_str, args);
|
|
return custom_string(buf.data(), buf.size(), alloc);
|
|
}
|
|
|
|
template <typename ...Args>
|
|
inline custom_string format(custom_allocator alloc,
|
|
fmt::string_view format_str,
|
|
const Args& ... args) {
|
|
return vformat(alloc, format_str, fmt::make_format_args(args...));
|
|
}
|
|
|
|
The allocator will be used for the output container only. If you are using named
|
|
arguments, the container that stores pointers to them will be allocated using
|
|
the default allocator. Also floating-point formatting falls back on ``sprintf``
|
|
which may do allocations.
|
|
|
|
.. _ranges-api:
|
|
|
|
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, ", "));
|
|
|
|
.. _chrono-api:
|
|
|
|
Date and Time Formatting
|
|
========================
|
|
|
|
The library supports `strftime
|
|
<http://en.cppreference.com/w/cpp/chrono/c/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 <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_.
|
|
|
|
.. _compile-api:
|
|
|
|
Format string compilation
|
|
=========================
|
|
|
|
``fmt/compile.h`` provides format string compilation support. Format strings
|
|
are parsed at compile time and converted into efficient formatting code. 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.
|
|
|
|
.. doxygendefine:: FMT_COMPILE
|
|
|
|
.. _ostream-api:
|
|
|
|
``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"
|
|
|
|
.. doxygenfunction:: print(std::basic_ostream<Char>&, const S&, Args&&...)
|
|
|
|
.. _printf-api:
|
|
|
|
``printf`` Formatting
|
|
=====================
|
|
|
|
The header ``fmt/printf.h`` provides ``printf``-like formatting functionality.
|
|
The following functions use `printf format string syntax
|
|
<http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ 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.
|
|
|
|
.. doxygenfunction:: printf(const S&, const Args&...)
|
|
|
|
.. doxygenfunction:: fprintf(std::FILE *, const S&, const Args&...)
|
|
|
|
.. doxygenfunction:: fprintf(std::basic_ostream<Char>&, const S&, const Args&...)
|
|
|
|
.. doxygenfunction:: sprintf(const S&, const Args&...)
|
|
|
|
Compatibility with C++20 ``std::format``
|
|
========================================
|
|
|
|
{fmt} implements nearly all of the `C++20 formatting library
|
|
<https://en.cppreference.com/w/cpp/utility/format>`_ with the following
|
|
differences:
|
|
|
|
* Names are defined in the ``fmt`` namespace instead of ``std`` 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.
|