- Restored ABI compatibility with version 8.0.x (#2695, #2696). Thanks @saraedum (Julian Rüth).
- Fixed chrono formatting on big endian systems (#2698, #2699). Thanks @phprus (Vladislav Shchapov) and @xvitaly (Vitaly Zaitsev).
- Fixed a linkage error with mingw (#2691, #2692). Thanks @rbberger (Richard Berger).
Optimized chrono formatting (#2500, #2537, #2541, #2544, #2550, #2551, #2576, #2577, #2586, #2591, #2594, #2602, #2617, #2628, #2633, #2670, #2671).
Processing of some specifiers such as
%z
and%Y
is now up to 10-20 times faster, for example on GCC 11 with libstdc++:---------------------------------------------------------------------------- Benchmark Before After ---------------------------------------------------------------------------- FMTFormatter_z 261 ns 26.3 ns FMTFormatterCompile_z 246 ns 11.6 ns FMTFormatter_Y 263 ns 26.1 ns FMTFormatterCompile_Y 244 ns 10.5 ns ----------------------------------------------------------------------------
Thanks @phprus (Vladislav Shchapov) and @toughengineer (Pavel Novikov).
Implemented subsecond formatting for chrono durations (#2623). For example (godbolt):
#include <fmt/chrono.h> int main() { fmt::print("{:%S}", std::chrono::milliseconds(1234)); }
prints "01.234".
Thanks @matrackif.
Fixed handling of precision 0 when formatting chrono durations (#2587, #2588). Thanks @lukester1975.
Fixed an overflow on invalid inputs in the
tm
formatter (#2564). Thanks @phprus (Vladislav Shchapov).Added
fmt::group_digits
that formats integers with a non-localized digit separator (comma) for groups of three digits. For example (godbolt):#include <fmt/format.h> int main() { fmt::print("{} dollars", fmt::group_digits(1000000)); }
prints "1,000,000 dollars".
Added support for faint, conceal, reverse and blink text styles (#2394):
blink.mp4
Thanks @benit8 (Benoît Lormeau) and @data-man (Dmitry Atamanov).
Added experimental support for compile-time floating point formatting (#2426, #2470). It is currently limited to the header-only mode. Thanks @alexezeder (Alexey Ochapov).
Added UDL-based named argument support to compile-time format string checks (#2640, #2649). For example (godbolt):
#include <fmt/format.h> int main() { using namespace fmt::literals; fmt::print("{answer:s}", "answer"_a=42); }
gives a compile-time error on compilers with C++20
consteval
and non-type template parameter support (gcc 10+) becauses
is not a valid format specifier for an integer.Thanks @alexezeder (Alexey Ochapov).
Implemented escaping of string range elements. For example (godbolt):
#include <fmt/ranges.h> #include <vector> int main() { fmt::print("{}", std::vector<std::string>{"\naan"}); }
is now printed as:
["\naan"]
instead of:
[" aan"]
Switched to JSON-like representation of maps and sets for consistency with Python's
str.format
. For example (godbolt):#include <fmt/ranges.h> #include <map> int main() { fmt::print("{}", std::map<std::string, int>{{"answer", 42}}); }
is now printed as:
{"answer": 42}
Extended
fmt::join
to support C++20-only ranges (#2549). Thanks @BRevzin (Barry Revzin).Optimized handling of non-const-iterable ranges and implemented initial support for non-const-formattable types.
Disabled implicit conversions of scoped enums to integers that was accidentally introduced in earlier versions (#1841).
Deprecated implicit conversion of
[const] signed char*
and[const] unsigned char*
to C strings.Deprecated
_format
, a legacy UDL-based format API (#2646). Thanks @alexezeder (Alexey Ochapov).Marked
format
,formatted_size
andto_string
as[[nodiscard]]
(#2612). @0x8000-0000 (Florin Iucha).Added missing diagnostic when trying to format function and member pointers as well as objects convertible to pointers which is explicitly disallowed (#2598, #2609, #2610). Thanks @AlexGuteniev (Alex Guteniev).
Optimized writing to a contiguous buffer with
format_to_n
(#2489). Thanks @Roman-Koshelev.Optimized writing to non-
char
buffers (#2477). Thanks @Roman-Koshelev.Decimal point is now localized when using the
L
specifier.Improved floating point formatter implementation (#2498, #2499). Thanks @Roman-Koshelev.
Fixed handling of very large precision in fixed format (#2616).
Made a table of cached powers used in FP formatting static (#2509). Thanks @jk-jeon (Junekey Jeon).
Resolved a lookup ambiguity with C++20 format-related functions due to ADL (#2639, #2641). Thanks @mkurdej (Marek Kurdej).
Removed unnecessary inline namespace qualification (#2642, #2643). Thanks @mkurdej (Marek Kurdej).
Implemented argument forwarding in
format_to_n
(#2462, #2463). Thanks @owent (WenTao Ou).Fixed handling of implicit conversions in
fmt::to_string
and format string compilation (#2565).Changed the default access mode of files created by
fmt::output_file
to-rw-r--r--
for consistency withfopen
(#2530).Make
fmt::ostream::flush
public (#2435).Improved C++14/17 attribute detection (#2615). Thanks @AlexGuteniev (Alex Guteniev).
Improved
consteval
detection for MSVC (#2559). Thanks @DanielaE (Daniela Engert).Improved documentation (#2406, #2446, #2493, #2513, #2515, #2522, #2562, #2575, #2606, #2620, #2676). Thanks @sobolevn (Nikita Sobolev), @UnePierre (Max FERGER), @zhsj, @phprus (Vladislav Shchapov), @ericcurtin (Eric Curtin), @Lounarok.
Improved fuzzers and added a fuzzer for chrono timepoint formatting (#2461, #2469). @pauldreik (Paul Dreik),
Added the
FMT_SYSTEM_HEADERS
CMake option setting which marks {fmt}'s headers as system. It can be used to suppress warnings (#2644, #2651). Thanks @alexezeder (Alexey Ochapov).Added the Bazel build system support (#2505, #2516). Thanks @Vertexwahn.
Improved build configuration and tests (#2437, #2558, #2648, #2650, #2663, #2677). Thanks @DanielaE (Daniela Engert), @alexezeder (Alexey Ochapov), @phprus (Vladislav Shchapov).
Fixed various warnings and compilation issues (#2353, #2356, #2399, #2408, #2414, #2427, #2432, #2442, #2434, #2439, #2447, #2450, #2455, #2465, #2472, #2474, #2476, #2478, #2479, #2481, #2482, #2483, #2490, #2491, #2510, #2518, #2528, #2529, #2539, #2540, #2545, #2555, #2557, #2570, #2573, #2582, #2605, #2611, #2647, #2627, #2630, #2635, #2638, #2653, #2654, #2661, #2664, #2684). Thanks @DanielaE (Daniela Engert), @mwinterb, @cdacamar (Cameron DaCamara), @TrebledJ (Johnathan), @bodomartin (brm), @cquammen (Cory Quammen), @white238 (Chris White), @mmarkeloff (Max), @palacaze (Pierre-Antoine Lacaze), @jcelerier (Jean-Michaël Celerier), @mborn-adi (Mathias Born), @BrukerJWD (Jonathan W), @spyridon97 (Spiros Tsalikis), @phprus (Vladislav Shchapov), @oliverlee (Oliver Lee), @joshessman-llnl (Josh Essman), @akohlmey (Axel Kohlmeyer), @timkalu, @olupton (Olli Lupton), @Acretock, @alexezeder (Alexey Ochapov), @andrewcorrigan (Andrew Corrigan), @lucpelletier, @HazardyKnusperkeks (Björn Schäpers).
- Fixed the version number in the inline namespace (#2374).
- Added a missing presentation type check for
std::string
(#2402). - Fixed a linkage error when mixing code built with clang and gcc (#2377).
- Fixed documentation issues (#2396, #2403, #2406). Thanks @mkurdej (Marek Kurdej).
- Removed dead code in FP formatter ( #2398). Thanks @javierhonduco (Javier Honduvilla Coto).
- Fixed various warnings and compilation issues (#2351, #2359, #2365, #2368, #2370, #2376, #2381, #2382, #2386, #2389, #2395, #2397, #2400, #2401, #2407). Thanks @zx2c4 (Jason A. Donenfeld), @AidanSun05 (Aidan Sun), @mattiasljungstrom (Mattias Ljungström), @joemmett (Jonathan Emmett), @erengy (Eren Okka), @patlkli (Patrick Geltinger), @gsjaardema (Greg Sjaardema), @phprus (Vladislav Shchapov).
Enabled compile-time format string checks by default. For example (godbolt):
#include <fmt/core.h> int main() { fmt::print("{:d}", "I am not a number"); }
gives a compile-time error on compilers with C++20
consteval
support (gcc 10+, clang 11+) becaused
is not a valid format specifier for a string.To pass a runtime string wrap it in
fmt::runtime
:fmt::print(fmt::runtime("{:d}"), "I am not a number");
Added compile-time formatting (#2019, #2044, #2056, #2072, #2075, #2078, #2129, #2326). For example (godbolt):
#include <fmt/compile.h> consteval auto compile_time_itoa(int value) -> std::array<char, 10> { auto result = std::array<char, 10>(); fmt::format_to(result.data(), FMT_COMPILE("{}"), value); return result; } constexpr auto answer = compile_time_itoa(42);
Most of the formatting functionality is available at compile time with a notable exception of floating-point numbers and pointers. Thanks @alexezeder (Alexey Ochapov).
Optimized handling of format specifiers during format string compilation. For example, hexadecimal formatting (
"{:x}"
) is now 3-7x faster than before when usingformat_to
with format string compilation and a stack-allocated buffer (#1944).Before (7.1.3):
---------------------------------------------------------------------------- Benchmark Time CPU Iterations ---------------------------------------------------------------------------- FMTCompileOld/0 15.5 ns 15.5 ns 43302898 FMTCompileOld/42 16.6 ns 16.6 ns 43278267 FMTCompileOld/273123 18.7 ns 18.6 ns 37035861 FMTCompileOld/9223372036854775807 19.4 ns 19.4 ns 35243000 ----------------------------------------------------------------------------
After (8.x):
---------------------------------------------------------------------------- Benchmark Time CPU Iterations ---------------------------------------------------------------------------- FMTCompileNew/0 1.99 ns 1.99 ns 360523686 FMTCompileNew/42 2.33 ns 2.33 ns 279865664 FMTCompileNew/273123 3.72 ns 3.71 ns 190230315 FMTCompileNew/9223372036854775807 5.28 ns 5.26 ns 130711631 ----------------------------------------------------------------------------
It is even faster than
std::to_chars
from libc++ compiled with clang on macOS:---------------------------------------------------------------------------- Benchmark Time CPU Iterations ---------------------------------------------------------------------------- ToChars/0 4.42 ns 4.41 ns 160196630 ToChars/42 5.00 ns 4.98 ns 140735201 ToChars/273123 7.26 ns 7.24 ns 95784130 ToChars/9223372036854775807 8.77 ns 8.75 ns 75872534 ----------------------------------------------------------------------------
In other cases, especially involving
std::string
construction, the speed up is usually lower because handling format specifiers takes a smaller fraction of the total time.Added the
_cf
user-defined literal to represent a compiled format string. It can be used instead of theFMT_COMPILE
macro (#2043, #2242):#include <fmt/compile.h> using namespace fmt::literals; auto s = fmt::format(FMT_COMPILE("{}"), 42); // 🙁 not modern auto s = fmt::format("{}"_cf, 42); // 🙂 modern as hell
It requires compiler support for class types in non-type template parameters (a C++20 feature) which is available in GCC 9.3+. Thanks @alexezeder (Alexey Ochapov).
Format string compilation now requires
format
functions offormatter
specializations for user-defined types to beconst
:template <> struct fmt::formatter<my_type>: formatter<string_view> { template <typename FormatContext> auto format(my_type obj, FormatContext& ctx) const { // Note const here. // ... } };
Added UDL-based named argument support to format string compilation (#2243, #2281). For example:
#include <fmt/compile.h> using namespace fmt::literals; auto s = fmt::format(FMT_COMPILE("{answer}"), "answer"_a = 42);
Here the argument named "answer" is resolved at compile time with no runtime overhead. Thanks @alexezeder (Alexey Ochapov).
Added format string compilation support to
fmt::print
(#2280, #2304). Thanks @alexezeder (Alexey Ochapov).Added initial support for compiling {fmt} as a C++20 module (#2235, #2240, #2260, #2282, #2283, #2288, #2298, #2306, #2307, #2309, #2318, #2324, #2332, #2340). Thanks @DanielaE (Daniela Engert).
Made symbols private by default reducing shared library size (#2301). For example there was a ~15% reported reduction on one platform. Thanks @sergiud (Sergiu Deitsch).
Optimized includes making the result of preprocessing
fmt/format.h
~20% smaller with libstdc++/C++20 and slightly improving build times (#1998).Added support of ranges with non-const
begin
/end
(#1953). Thanks @kitegi (sarah).Added support of
std::byte
and other formattable types tofmt::join
(#1981, #2040, #2050, #2262). For example:#include <fmt/format.h> #include <cstddef> #include <vector> int main() { auto bytes = std::vector{std::byte(4), std::byte(2)}; fmt::print("{}", fmt::join(bytes, "")); }
prints "42".
Thanks @kamibo (Camille Bordignon).
Implemented the default format for
std::chrono::system_clock
(#2319, #2345). For example:#include <fmt/chrono.h> int main() { fmt::print("{}", std::chrono::system_clock::now()); }
prints "2021-06-18 15:22:00" (the output depends on the current date and time). Thanks @sunmy2019.
Made more chrono specifiers locale independent by default. Use the
'L'
specifier to get localized formatting. For example:#include <fmt/chrono.h> int main() { std::locale::global(std::locale("ru_RU.UTF-8")); auto monday = std::chrono::weekday(1); fmt::print("{}\n", monday); // prints "Mon" fmt::print("{:L}\n", monday); // prints "пн" }
Improved locale handling in chrono formatting (#2337, #2349, #2350). Thanks @phprus (Vladislav Shchapov).
Deprecated
fmt/locale.h
moving the formatting functions that take a locale tofmt/format.h
(char
) andfmt/xchar
(other overloads). This doesn't introduce a dependency on<locale>
so there is virtually no compile time effect.Deprecated an undocumented
format_to
overload that takesbasic_memory_buffer
.Made parameter order in
vformat_to
consistent withformat_to
(#2327).Added support for time points with arbitrary durations (#2208). For example:
#include <fmt/chrono.h> int main() { using tp = std::chrono::time_point< std::chrono::system_clock, std::chrono::seconds>; fmt::print("{:%S}", tp(std::chrono::seconds(42))); }
prints "42".
Formatting floating-point numbers no longer produces trailing zeros by default for consistency with
std::format
. For example:#include <fmt/core.h> int main() { fmt::print("{0:.3}", 1.1); }
prints "1.1". Use the
'#'
specifier to keep trailing zeros.Dropped a limit on the number of elements in a range and replaced
{}
with[]
as range delimiters for consistency with Python'sstr.format
.The
'L'
specifier for locale-specific numeric formatting can now be combined with presentation specifiers as instd::format
. For example:#include <fmt/core.h> #include <locale> int main() { std::locale::global(std::locale("fr_FR.UTF-8")); fmt::print("{0:.2Lf}", 0.42); }
prints "0,42". The deprecated
'n'
specifier has been removed.Made the
0
specifier ignored for infinity and NaN (#2305, #2310). Thanks @Liedtke (Matthias Liedtke).Made the hexfloat formatting use the right alignment by default (#2308, #2317). Thanks @Liedtke (Matthias Liedtke).
Removed the deprecated numeric alignment (
'='
). Use the'0'
specifier instead.Removed the deprecated
fmt/posix.h
header that has been replaced withfmt/os.h
.Removed the deprecated
format_to_n_context
,format_to_n_args
andmake_format_to_n_args
. They have been replaced withformat_context
,format_args` and ``make_format_args
respectively.Moved
wchar_t
-specific functions and types tofmt/xchar.h
. You can defineFMT_DEPRECATED_INCLUDE_XCHAR
to automatically includefmt/xchar.h
fromfmt/format.h
but this will be disabled in the next major release.Fixed handling of the
'+'
specifier in localized formatting (#2133).Added support for the
's'
format specifier that gives textual representation ofbool
(#2094, #2109). For example:#include <fmt/core.h> int main() { fmt::print("{:s}", true); }
prints "true". Thanks @powercoderlol (Ivan Polyakov).
Made
fmt::ptr
work with function pointers (#2131). For example:#include <fmt/format.h> int main() { fmt::print("My main: {}\n", fmt::ptr(main)); }
Thanks @mikecrowe (Mike Crowe).
The undocumented support for specializing
formatter
for pointer types has been removed.Fixed
fmt::formatted_size
with format string compilation (#2141, #2161). Thanks @alexezeder (Alexey Ochapov).Fixed handling of empty format strings during format string compilation (#2042):
auto s = fmt::format(FMT_COMPILE(""));
Thanks @alexezeder (Alexey Ochapov).
Fixed handling of enums in
fmt::to_string
(#2036).Improved width computation (#2033, #2091). For example:
#include <fmt/core.h> int main() { fmt::print("{:-<10}{}\n", "你好", "世界"); fmt::print("{:-<10}{}\n", "hello", "world"); }
prints
on a modern terminal.
The experimental fast output stream (
fmt::ostream
) is now truncated by default for consistency withfopen
(#2018). For example:#include <fmt/os.h> int main() { fmt::ostream out1 = fmt::output_file("guide"); out1.print("Zaphod"); out1.close(); fmt::ostream out2 = fmt::output_file("guide"); out2.print("Ford"); }
writes "Ford" to the file "guide". To preserve the old file content if any pass
fmt::file::WRONLY | fmt::file::CREATE
flags tofmt::output_file
.Fixed moving of
fmt::ostream
that holds buffered data (#2197, #2198). Thanks @vtta.Replaced the
fmt::system_error
exception with a function of the same name that constructsstd::system_error
(#2266).Replaced the
fmt::windows_error
exception with a function of the same name that constructsstd::system_error
with the category returned byfmt::system_category()
(#2274, #2275). The latter is similar tostd::sytem_category
but correctly handles UTF-8. Thanks @phprus (Vladislav Shchapov).Replaced
fmt::error_code
withstd::error_code
and made it formattable (#2269, #2270, #2273). Thanks @phprus (Vladislav Shchapov).Added speech synthesis support (#2206).
Made
format_to
work with a memory buffer that has a custom allocator (#2300). Thanks @voxmea.Added
Allocator::max_size
support tobasic_memory_buffer
. (#1960). Thanks @phprus (Vladislav Shchapov).Added wide string support to
fmt::join
(#2236). Thanks @crbrz.Made iterators passed to
formatter
specializations via a format context satisfy C++20std::output_iterator
requirements (#2156, #2158, #2195, #2204). Thanks @randomnetcat (Jason Cobb).Optimized the
printf
implementation (#1982, #1984, #2016, #2164). Thanks @rimathia and @moiwi.Improved detection of
constexpr
char_traits
(#2246, #2257). Thanks @phprus (Vladislav Shchapov).Fixed writing to
stdout
when it is redirected toNUL
on Windows (#2080).Fixed exception propagation from iterators (#2097).
Improved
strftime
error handling (#2238, #2244). Thanks @yumeyao.Stopped using deprecated GCC UDL template extension.
Added
fmt/args.h
to the install target (#2096).Error messages are now passed to assert when exceptions are disabled (#2145). Thanks @NobodyXu (Jiahao XU).
Added the
FMT_MASTER_PROJECT
CMake option to control build and install targets when {fmt} is included viaadd_subdirectory
(#2098, #2100). Thanks @randomizedthinking.Improved build configuration (#2026, #2122). Thanks @luncliff (Park DongHa) and @ibaned (Dan Ibanez).
Fixed various warnings and compilation issues (#1947, #1959, #1963, #1965, #1966, #1974, #1975, #1990, #2000, #2001, #2002, #2004, #2006, #2009, #2010, #2038, #2039, #2047, #2053, #2059, #2065, #2067, #2068, #2073, #2103, #2105, #2106, #2107, #2116, #2117, #2118, #2119, #2127, #2128, #2140, #2142, #2143, #2144, #2147, #2148, #2149, #2152, #2160, #2170, #2175, #2176, #2177, #2178, #2179, #2180, #2181, #2183, #2184, #2185, #2186, #2187, #2190, #2192, #2194, #2205, #2210, #2211, #2215, #2216, #2218, #2220, #2228, #2229, #2230, #2233, #2239, #2248, #2252, #2253, #2255, #2261, #2278, #2284, #2287, #2289, #2290, #2293, #2295, #2296, #2297, #2311, #2313, #2315, #2320, #2321, #2323, #2328, #2329, #2333, #2338, #2341). Thanks @darklukee, @fagg (Ashton Fagg), @killerbot242 (Lieven de Cock), @jgopel (Jonathan Gopel), @yeswalrus (Walter Gray), @Finkman, @HazardyKnusperkeks (Björn Schäpers), @dkavolis (Daumantas Kavolis), @concatime (Issam Maghni), @chronoxor (Ivan Shynkarenka), @summivox (Yin Zhong), @yNeo, @Apache-HB (Elliot), @alexezeder (Alexey Ochapov), @toojays (John Steele Scott), @Brainy0207, @vadz (VZ), @imsherlock (Ryan Sherlock), @phprus (Vladislav Shchapov), @white238 (Chris White), @yafshar (Yaser Afshar), @BillyDonahue (Billy Donahue), @jstaahl, @denchat, @DanielaE (Daniela Engert), @ilyakurdyukov (Ilya Kurdyukov), @ilmai, @JessyDL (Jessy De Lannoit), @sergiud (Sergiu Deitsch), @mwinterb, @sven-herrmann, @jmelas (John Melas), @twoixter (Jose Miguel Pérez), @crbrz, @upsj (Tobias Ribizel).
Improved documentation (#1986, #2051, #2057, #2081, #2084, #2312). Thanks @imba-tjd (谭九鼎), @0x416c69 (AlιAѕѕaѕѕιN), @mordante.
Continuous integration and test improvements (#1969, #1991, #2020, #2110, #2114, #2196, #2217, #2247, #2256, #2336, #2346). Thanks @jgopel (Jonathan Gopel), @alexezeder (Alexey Ochapov) and @DanielaE (Daniela Engert).
- Fixed handling of buffer boundaries in
format_to_n
(#1996, #2029). - Fixed linkage errors when linking with a shared library (#2011).
- Reintroduced ostream support to range formatters (#2014).
- Worked around an issue with mixing std versions in gcc (#2017).
- Fixed floating point formatting with large precision (#1976).
- Fixed ABI compatibility with 7.0.x (#1961).
- Added the
FMT_ARM_ABI_COMPATIBILITY
macro to work around ABI incompatibility between GCC and Clang on ARM (#1919). - Worked around a SFINAE bug in GCC 8 (#1957).
- Fixed linkage errors when building with GCC's LTO (#1955).
- Fixed a compilation error when building without
__builtin_clz
or equivalent (#1968). Thanks @tohammer (Tobias Hammer). - Fixed a sign conversion warning (#1964). Thanks @OptoCloud.
Switched from Grisu3 to Dragonbox for the default floating-point formatting which gives the shortest decimal representation with round-trip guarantee and correct rounding (#1882, #1887, #1894). This makes {fmt} up to 20-30x faster than common implementations of
std::ostringstream
andsprintf
on dtoa-benchmark and faster than double-conversion and Ryū:It is possible to get even better performance at the cost of larger binary size by compiling with the
FMT_USE_FULL_CACHE_DRAGONBOX
macro set to 1.Thanks @jk-jeon (Junekey Jeon).
Added an experimental unsynchronized file output API which, together with format string compilation, can give 5-9 times speed up compared to fprintf on common platforms (godbolt):
#include <fmt/os.h> int main() { auto f = fmt::output_file("guide"); f.print("The answer is {}.", 42); }
Added a formatter for
std::chrono::time_point<system_clock>
(#1819, #1837). For example (godbolt):#include <fmt/chrono.h> int main() { auto now = std::chrono::system_clock::now(); fmt::print("The time is {:%H:%M:%S}.\n", now); }
Thanks @adamburgess (Adam Burgess).
Added support for ranges with non-const
begin
/end
tofmt::join
(#1784, #1786). For example (godbolt):#include <fmt/ranges.h> #include <range/v3/view/filter.hpp> int main() { using std::literals::string_literals::operator""s; auto strs = std::array{"a"s, "bb"s, "ccc"s}; auto range = strs | ranges::views::filter( [] (const std::string &x) { return x.size() != 2; } ); fmt::print("{}\n", fmt::join(range, "")); }
prints "accc".
Thanks @tonyelewis (Tony E Lewis).
Added a
memory_buffer::append
overload that takes a range (#1806). Thanks @BRevzin (Barry Revzin).Improved handling of single code units in
FMT_COMPILE
. For example:#include <fmt/compile.h> char* f(char* buf) { return fmt::format_to(buf, FMT_COMPILE("x{}"), 42); }
compiles to just (godbolt):
_Z1fPc: movb $120, (%rdi) xorl %edx, %edx cmpl $42, _ZN3fmt2v76detail10basic_dataIvE23zero_or_powers_of_10_32E+8(%rip) movl $3, %eax seta %dl subl %edx, %eax movzwl _ZN3fmt2v76detail10basic_dataIvE6digitsE+84(%rip), %edx cltq addq %rdi, %rax movw %dx, -2(%rax) ret
Here a single
mov
instruction writes'x'
($120
) to the output buffer.Added dynamic width support to format string compilation (#1809).
Improved error reporting for unformattable types: now you'll get the type name directly in the error message instead of the note:
#include <fmt/core.h> struct how_about_no {}; int main() { fmt::print("{}", how_about_no()); }
Error (godbolt):
fmt/core.h:1438:3: error: static_assert failed due to requirement 'fmt::v7::formattable<how_about_no>()' "Cannot format an argument. To make type T formattable provide a formatter<T> specialization: https://fmt.dev/latest/api.html#udt" ...
Added the make_args_checked function template that allows you to write formatting functions with compile-time format string checks and avoid binary code bloat (godbolt):
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);
Replaced
snprintf
fallback with a faster internal IEEE 754float
anddouble
formatter for arbitrary precision. For example (godbolt):#include <fmt/core.h> int main() { fmt::print("{:.500}\n", 4.9406564584124654E-324); }
prints
4.9406564584124654417656879286822137236505980261432476442558568250067550727020875186529983636163599237979656469544571773092665671035593979639877479601078187812630071319031140452784581716784898210368871863605699873072305000638740915356498438731247339727316961514003171538539807412623856559117102665855668676818703956031062493194527159149245532930545654440112748012970999954193198940908041656332452475714786901472678015935523861155013480352649347201937902681071074917033322268447533357208324319360923829e-324
.Made
format_to_n
andformatted_size
part of the core API (godbolt):#include <fmt/core.h> int main() { char buffer[10]; auto result = fmt::format_to_n(buffer, sizeof(buffer), "{}", 42); }
Added
fmt::format_to_n
overload with format string compilation (#1764, #1767, #1869). For example (godbolt):#include <fmt/compile.h> int main() { char buffer[8]; fmt::format_to_n(buffer, sizeof(buffer), FMT_COMPILE("{}"), 42); }
Thanks @Kurkin (Dmitry Kurkin), @alexezeder (Alexey Ochapov).
Added
fmt::format_to
overload that taketext_style
(#1593, #1842, #1843). For example (godbolt):#include <fmt/color.h> int main() { std::string out; fmt::format_to(std::back_inserter(out), fmt::emphasis::bold | fg(fmt::color::red), "The answer is {}.", 42); }
Thanks @Naios (Denis Blank).
Made the
'#'
specifier emit trailing zeros in addition to the decimal point (#1797). For example (godbolt):#include <fmt/core.h> int main() { fmt::print("{:#.2g}", 0.5); }
prints
0.50
.Changed the default floating point format to not include
.0
for consistency withstd::format
andstd::to_chars
(#1893, #1943). It is possible to get the decimal point and trailing zero with the#
specifier.Fixed an issue with floating-point formatting that could result in addition of a non-significant trailing zero in rare cases e.g.
1.00e-34
instead of1.0e-34
(#1873, #1917).Made
fmt::to_string
fallback onostream
insertion operator if theformatter
specialization is not provided (#1815, #1829). Thanks @alexezeder (Alexey Ochapov).Added support for the append mode to the experimental file API and improved
fcntl.h
detection. (#1847, #1848). Thanks @t-wiser.Fixed handling of types that have both an implicit conversion operator and an overloaded
ostream
insertion operator (#1766).Fixed a slicing issue in an internal iterator type (#1822). Thanks @BRevzin (Barry Revzin).
Fixed an issue in locale-specific integer formatting (#1927).
Improved
FMT_ALWAYS_INLINE
(#1878). Thanks @jk-jeon (Junekey Jeon).Removed dependency on
windows.h
(#1900). Thanks @bernd5 (Bernd Baumanns).Optimized counting of decimal digits on MSVC (#1890). Thanks @mwinterb.
Improved documentation (#1772, #1775, #1792, #1838, #1888, #1918, #1939). Thanks @leolchat (Léonard Gérard), @pepsiman (Malcolm Parsons), @Klaim (Joël Lamotte), @ravijanjam (Ravi J), @francesco-st, @udnaan (Adnan).
Added the
FMT_REDUCE_INT_INSTANTIATIONS
CMake option that reduces the binary code size at the cost of some integer formatting performance. This can be useful for extremely memory-constrained embedded systems (#1778, #1781). Thanks @kammce (Khalil Estell).Added the
FMT_USE_INLINE_NAMESPACES
macro to control usage of inline namespaces (#1945). Thanks @darklukee.Improved build configuration (#1760, #1770, #1779, #1783, #1823). Thanks @dvetutnev (Dmitriy Vetutnev), @xvitaly (Vitaly Zaitsev), @tambry (Raul Tambre), @medithe, @martinwuehrer (Martin Wührer).
Fixed various warnings and compilation issues (#1790, #1802, #1808, #1810, #1811, #1812, #1814, #1816, #1817, #1818, #1825, #1836, #1855, #1856, #1860, #1877, #1879, #1880, #1896, #1897, #1898, #1904, #1908, #1911, #1912, #1928, #1929, #1935, #1937, #1942, #1949). Thanks @TheQwertiest, @medithe, @martinwuehrer (Martin Wührer), @n16h7hunt3r, @Othereum (Seokjin Lee), @gsjaardema (Greg Sjaardema), @AlexanderLanin (Alexander Lanin), @gcerretani (Giovanni Cerretani), @chronoxor (Ivan Shynkarenka), @noizefloor (Jan Schwers), @akohlmey (Axel Kohlmeyer), @jk-jeon (Junekey Jeon), @rimathia, @rglarix (Riccardo Ghetta (larix)), @moiwi, @heckad (Kazantcev Andrey), @MarcDirven. @BartSiwek (Bart Siwek), @darklukee.
- Worked around broken
numeric_limits
for 128-bit integers (#1787). - Added error reporting on missing named arguments (#1796).
- Stopped using 128-bit integers with clang-cl (#1800). Thanks @Kingcom.
- Fixed issues in locale-specific integer formatting (#1782, #1801).
- Worked around broken
numeric_limits
for 128-bit integers (#1725). - Fixed compatibility with CMake 3.4 (#1779).
- Fixed handling of digit separators in locale-specific formatting (#1782).
- Updated the inline version namespace name.
- Worked around a gcc bug in mangling of alias templates (#1753).
- Fixed a linkage error on Windows (#1757). Thanks @Kurkin (Dmitry Kurkin).
- Fixed minor issues with the documentation.
Reduced the library size. For example, on macOS a stripped test binary statically linked with {fmt} shrank from ~368k to less than 100k.
Added a simpler and more efficient format string compilation API:
#include <fmt/compile.h> // Converts 42 into std::string using the most efficient method and no // runtime format string processing. std::string s = fmt::format(FMT_COMPILE("{}"), 42);
The old
fmt::compile
API is now deprecated.Optimized integer formatting:
format_to
with format string compilation and a stack-allocated buffer is now faster than to_chars on both libc++ and libstdc++.Optimized handling of small format strings. For example,
fmt::format("Result: {}: ({},{},{},{})", str1, str2, str3, str4, str5)
is now ~40% faster (#1685).
Applied extern templates to improve compile times when using the core API and
fmt/format.h
(#1452). For example, on macOS with clang the compile time of a test translation unit dropped from 2.3s to 0.3s with-O2
and from 0.6s to 0.3s with the default settings (-O0
).Before (
-O2
):% time c++ -c test.cc -I include -std=c++17 -O2 c++ -c test.cc -I include -std=c++17 -O2 2.22s user 0.08s system 99% cpu 2.311 total
After (
-O2
):% time c++ -c test.cc -I include -std=c++17 -O2 c++ -c test.cc -I include -std=c++17 -O2 0.26s user 0.04s system 98% cpu 0.303 total
Before (default):
% time c++ -c test.cc -I include -std=c++17 c++ -c test.cc -I include -std=c++17 0.53s user 0.06s system 98% cpu 0.601 total
After (default):
% time c++ -c test.cc -I include -std=c++17 c++ -c test.cc -I include -std=c++17 0.24s user 0.06s system 98% cpu 0.301 total
It is still recommended to use
fmt/core.h
instead offmt/format.h
but the compile time difference is now smaller. Thanks @alex3d for the suggestion.Named arguments are now stored on stack (no dynamic memory allocations) and the compiled code is more compact and efficient. For example
#include <fmt/core.h> int main() { fmt::print("The answer is {answer}\n", fmt::arg("answer", 42)); }
compiles to just (godbolt)
.LC0: .string "answer" .LC1: .string "The answer is {answer}\n" main: sub rsp, 56 mov edi, OFFSET FLAT:.LC1 mov esi, 23 movabs rdx, 4611686018427387905 lea rax, [rsp+32] lea rcx, [rsp+16] mov QWORD PTR [rsp+8], 1 mov QWORD PTR [rsp], rax mov DWORD PTR [rsp+16], 42 mov QWORD PTR [rsp+32], OFFSET FLAT:.LC0 mov DWORD PTR [rsp+40], 0 call fmt::v6::vprint(fmt::v6::basic_string_view<char>, fmt::v6::format_args) xor eax, eax add rsp, 56 ret .L.str.1: .asciz "answer"
Implemented compile-time checks for dynamic width and precision (#1614):
#include <fmt/format.h> int main() { fmt::print(FMT_STRING("{0:{1}}"), 42); }
now gives a compilation error because argument 1 doesn't exist:
In file included from test.cc:1: include/fmt/format.h:2726:27: error: constexpr variable 'invalid_format' must be initialized by a constant expression FMT_CONSTEXPR_DECL bool invalid_format = ^ ... include/fmt/core.h:569:26: note: in call to '&checker(s, {}).context_->on_error(&"argument not found"[0])' if (id >= num_args_) on_error("argument not found"); ^
Added sentinel support to
fmt::join
(#1689)struct zstring_sentinel {}; bool operator==(const char* p, zstring_sentinel) { return *p == '\0'; } bool operator!=(const char* p, zstring_sentinel) { return *p != '\0'; } struct zstring { const char* p; const char* begin() const { return p; } zstring_sentinel end() const { return {}; } }; auto s = fmt::format("{}", fmt::join(zstring{"hello"}, "_")); // s == "h_e_l_l_o"
Thanks @BRevzin (Barry Revzin).
Added support for named arguments,
clear
andreserve
todynamic_format_arg_store
(#1655, #1663, #1674, #1677). Thanks @vsolontsov-ll (Vladimir Solontsov).Added support for the
'c'
format specifier to integral types for compatibility withstd::format
(#1652).Replaced the
'n'
format specifier with'L'
for compatibility withstd::format
(#1624). The'n'
specifier can be enabled via theFMT_DEPRECATED_N_SPECIFIER
macro.The
'='
format specifier is now disabled by default for compatibility withstd::format
. It can be enabled via theFMT_DEPRECATED_NUMERIC_ALIGN
macro.Removed the following deprecated APIs:
FMT_STRING_ALIAS
andfmt
macros - replaced byFMT_STRING
fmt::basic_string_view::char_type
- replaced byfmt::basic_string_view::value_type
convert_to_int
format_arg_store::types
*parse_context
- replaced by*format_parse_context
FMT_DEPRECATED_INCLUDE_OS
FMT_DEPRECATED_PERCENT
- incompatible withstd::format
*writer
- replaced by compiled format API
Renamed the
internal
namespace todetail
(#1538). The former is still provided as an alias if theFMT_USE_INTERNAL
macro is defined.Improved compatibility between
fmt::printf
with the standard specs (#1595, #1682, #1683, #1687, #1699). Thanks @rimathia.Fixed handling of
operator<<
overloads that usecopyfmt
(#1666).Added the
FMT_OS
CMake option to control inclusion of OS-specific APIs in the fmt target. This can be useful for embedded platforms (#1654, #1656). Thanks @kwesolowski (Krzysztof Wesolowski).Replaced
FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
with theFMT_FUZZ
macro to prevent interferring with fuzzing of projects using {fmt} (#1650). Thanks @asraa (Asra Ali).Fixed compatibility with emscripten (#1636, #1637). Thanks @ArthurSonzogni (Arthur Sonzogni).
Improved documentation (#704, #1643, #1660, #1681, #1691, #1706, #1714, #1721, #1739, #1740, #1741, #1751). Thanks @senior7515 (Alexander Gallego), @lsr0 (Lindsay Roberts), @puetzk (Kevin Puetz), @fpelliccioni (Fernando Pelliccioni), Alexey Kuzmenko, @jelly (jelle van der Waa), @claremacrae (Clare Macrae), @jiapengwen (文佳鹏), @gsjaardema (Greg Sjaardema), @alexey-milovidov.
Implemented various build configuration fixes and improvements (#1603, #1657, #1702, #1728). Thanks @scramsby (Scott Ramsby), @jtojnar (Jan Tojnar), @orivej (Orivej Desh), @flagarde.
Fixed various warnings and compilation issues (#1616, #1620, #1622, #1625, #1627, #1628, #1629, #1631, #1633, #1649, #1658, #1661, #1667, #1668, #1669, #1692, #1696, #1697, #1707, #1712, #1716, #1722, #1724, #1729, #1738, #1742, #1743, #1744, #1747, #1750). Thanks @gsjaardema (Greg Sjaardema), @gabime (Gabi Melman), @johnor (Johan), @Kurkin (Dmitry Kurkin), @invexed (James Beach), @peterbell10, @daixtrose (Markus Werle), @petrutlucian94 (Lucian Petrut), @Neargye (Daniil Goncharov), @ambitslix (Attila M. Szilagyi), @gabime (Gabi Melman), @erthink (Leonid Yuriev), @tohammer (Tobias Hammer), @0x8000-0000 (Florin Iucha).
- Fixed ostream support in
sprintf
(#1631). - Fixed type detection when using implicit conversion to
string_view
and ostreamoperator<<
inconsistently (#1662).
Improved error reporting when trying to format an object of a non-formattable type:
fmt::format("{}", S());
now gives:
include/fmt/core.h:1015:5: error: static_assert failed due to requirement 'formattable' "Cannot format argument. To make type T formattable provide a formatter<T> specialization: https://fmt.dev/latest/api.html#formatting-user-defined-types" static_assert( ^ ... note: in instantiation of function template specialization 'fmt::v6::format<char [3], S, char>' requested here fmt::format("{}", S()); ^
if
S
is not formattable.Reduced the library size by ~10%.
Always print decimal point if
#
is specified (#1476, #1498):fmt::print("{:#.0f}", 42.0);
now prints
42.
Implemented the
'L'
specifier for locale-specific numeric formatting to improve compatibility withstd::format
. The'n'
specifier is now deprecated and will be removed in the next major release.Moved OS-specific APIs such as
windows_error
fromfmt/format.h
tofmt/os.h
. You can defineFMT_DEPRECATED_INCLUDE_OS
to automatically includefmt/os.h
fromfmt/format.h
for compatibility but this will be disabled in the next major release.Added precision overflow detection in floating-point formatting.
Implemented detection of invalid use of
fmt::arg
.Used
type_identity
to block unnecessary template argument deduction. Thanks Tim Song.Improved UTF-8 handling (#1109):
fmt::print("┌{0:─^{2}}┐\n" "│{1: ^{2}}│\n" "└{0:─^{2}}┘\n", "", "Привет, мир!", 20);
now prints:
┌────────────────────┐ │ Привет, мир! │ └────────────────────┘
on systems that support Unicode.
Added experimental dynamic argument storage (#1170, #1584):
fmt::dynamic_format_arg_store<fmt::format_context> store; store.push_back("answer"); store.push_back(42); fmt::vprint("The {} is {}.\n", store);
prints:
The answer is 42.
Made
fmt::join
acceptinitializer_list
(#1591). Thanks @Rapotkinnik (Nikolay Rapotkin).Fixed handling of empty tuples (#1588).
Fixed handling of output iterators in
format_to_n
(#1506).Fixed formatting of
std::chrono::duration
types to wide output (#1533). Thanks @zeffy (pilao).Added const
begin
andend
overload to buffers (#1553). Thanks @dominicpoeschko.Added the ability to disable floating-point formatting via
FMT_USE_FLOAT
,FMT_USE_DOUBLE
andFMT_USE_LONG_DOUBLE
macros for extremely memory-constrained embedded system (#1590). Thanks @albaguirre (Alberto Aguirre).Made
FMT_STRING
work withconstexpr
string_view
(#1589). Thanks @scramsby (Scott Ramsby).Implemented a minor optimization in the format string parser (#1560). Thanks @IkarusDeveloper.
Improved attribute detection (#1469, #1475, #1576). Thanks @federico-busato (Federico), @chronoxor (Ivan Shynkarenka), @refnum.
Improved documentation (#1481, #1523). Thanks @JackBoosY (Jack·Boos·Yu), @imba-tjd (谭九鼎).
Fixed symbol visibility on Linux when compiling with
-fvisibility=hidden
(#1535). Thanks @milianw (Milian Wolff).Implemented various build configuration fixes and improvements (#1264, #1460, #1534, #1536, #1545, #1546, #1566, #1582, #1597, #1598). Thanks @ambitslix (Attila M. Szilagyi), @jwillikers (Jordan Williams), @stac47 (Laurent Stacul).
Fixed various warnings and compilation issues (#1433, #1461, #1470, #1480, #1485, #1492, #1493, #1504, #1505, #1512, #1515, #1516, #1518, #1519, #1520, #1521, #1522, #1524, #1530, #1531, #1532, #1539, #1547, #1548, #1554, #1567, #1568, #1569, #1571, #1573, #1575, #1581, #1583, #1586, #1587, #1594, #1596, #1604, #1606, #1607, #1609). Thanks @marti4d (Chris Martin), @iPherian, @parkertomatoes, @gsjaardema (Greg Sjaardema), @chronoxor (Ivan Shynkarenka), @DanielaE (Daniela Engert), @torsten48, @tohammer (Tobias Hammer), @lefticus (Jason Turner), @ryusakki (Haise), @adnsv (Alex Denisov), @fghzxm, @refnum, @pramodk (Pramod Kumbhar), @Spirrwell, @scramsby (Scott Ramsby).
- Fixed ABI compatibility with
libfmt.so.6.0.0
(#1471). - Fixed handling types convertible to
std::string_view
(#1451). Thanks @denizevrenci (Deniz Evrenci). - Made CUDA test an opt-in enabled via the
FMT_CUDA_TEST
CMake option. - Fixed sign conversion warnings (#1440). Thanks @0x8000-0000 (Florin Iucha).
- Fixed shared library build on Windows (#1443, #1445, #1446, #1450). Thanks @egorpugin (Egor Pugin), @bbolli (Beat Bolli).
- Added a missing decimal point in exponent notation with trailing zeros.
- Removed deprecated
format_arg_store::TYPES
.
{fmt} now formats IEEE 754
float
anddouble
using the shortest decimal representation with correct rounding by default:#include <cmath> #include <fmt/core.h> int main() { fmt::print("{}", M_PI); }
prints
3.141592653589793
.Made the fast binary to decimal floating-point formatter the default, simplified it and improved performance. {fmt} is now 15 times faster than libc++'s
std::ostringstream
, 11 times faster thanprintf
and 10% faster than double-conversion on dtoa-benchmark:Function
Time (ns)
Speedup
ostringstream
1,346.30
1.00x
ostrstream
1,195.74
1.13x
sprintf
995.08
1.35x
doubleconv
99.10
13.59x
fmt
88.34
15.24x
{fmt} no longer converts
float
arguments todouble
. In particular this improves the default (shortest) representation of floats and makesfmt::format
consistent withstd::format
specs (#1336, #1353, #1360, #1361):fmt::print("{}", 0.1f);
prints
0.1
instead of0.10000000149011612
.Thanks @orivej (Orivej Desh).
Made floating-point formatting output consistent with
printf
/iostreams (#1376, #1417).Added support for 128-bit integers (#1287):
fmt::print("{}", std::numeric_limits<__int128_t>::max());
prints
170141183460469231731687303715884105727
.Thanks @denizevrenci (Deniz Evrenci).
The overload of
print
that takestext_style
is now atomic, i.e. the output from different threads doesn't interleave (#1351). Thanks @tankiJong (Tanki Zhang).Made compile time in the header-only mode ~20% faster by reducing the number of template instantiations.
wchar_t
overload ofvprint
was moved fromfmt/core.h
tofmt/format.h
.Added an overload of
fmt::join
that works with tuples (#1322, #1330):#include <tuple> #include <fmt/ranges.h> int main() { std::tuple<char, int, float> t{'a', 1, 2.0f}; fmt::print("{}", t); }
prints
('a', 1, 2.0)
.Thanks @jeremyong (Jeremy Ong).
Changed formatting of octal zero with prefix from "00" to "0":
fmt::print("{:#o}", 0);
prints
0
.The locale is now passed to ostream insertion (
<<
) operators (#1406):#include <fmt/locale.h> #include <fmt/ostream.h> struct S { double value; }; std::ostream& operator<<(std::ostream& os, S s) { return os << s.value; } int main() { auto s = fmt::format(std::locale("fr_FR.UTF-8"), "{}", S{0.42}); // s == "0,42" }
Thanks @dlaugt (Daniel Laügt).
Locale-specific number formatting now uses grouping (#1393 #1394). Thanks @skrdaniel.
Fixed handling of types with deleted implicit rvalue conversion to
const char**
(#1421):struct mystring { operator const char*() const&; operator const char*() &; operator const char*() const&& = delete; operator const char*() && = delete; }; mystring str; fmt::print("{}", str); // now compiles
Enums are now mapped to correct underlying types instead of
int
(#1286). Thanks @agmt (Egor Seredin).Enum classes are no longer implicitly converted to
int
(#1424).Added
basic_format_parse_context
for consistency with C++20std::format
and deprecatedbasic_parse_context
.Fixed handling of UTF-8 in precision (#1389, #1390). Thanks @tajtiattila (Attila Tajti).
{fmt} can now be installed on Linux, macOS and Windows with Conda using its conda-forge package (#1410):
conda install -c conda-forge fmt
Thanks @tdegeus (Tom de Geus).
Added a CUDA test (#1285, #1317). Thanks @luncliff (Park DongHa) and @risa2000.
Improved documentation (#1276, #1291, #1296, #1315, #1332, #1337, #1395 #1418). Thanks @waywardmonkeys (Bruce Mitchener), @pauldreik (Paul Dreik), @jackoalan (Jack Andersen).
Various code improvements (#1358, #1407). Thanks @orivej (Orivej Desh), @dpacbach (David P. Sicilia),
Fixed compile-time format string checks for user-defined types (#1292).
Worked around a false positive in
unsigned-integer-overflow
sanitizer (#1377).Fixed various warnings and compilation issues (#1273, #1278, #1280, #1281, #1288, #1290, #1301, #1305, #1306, #1309, #1312, #1313, #1316, #1319, #1320, #1326, #1328, #1344, #1345, #1347, #1349, #1354, #1362, #1366, #1364, #1370, #1371, #1385, #1388, #1397, #1414, #1416, #1422 #1427, #1431, #1433). Thanks @hhb, @gsjaardema (Greg Sjaardema), @gabime (Gabi Melman), @neheb (Rosen Penev), @vedranmiletic (Vedran Miletić), @dkavolis (Daumantas Kavolis), @mwinterb, @orivej (Orivej Desh), @denizevrenci (Deniz Evrenci) @leonklingele, @chronoxor (Ivan Shynkarenka), @kent-tri, @0x8000-0000 (Florin Iucha), @marti4d (Chris Martin).
Switched to the MIT license with an optional exception that allows distributing binary code without attribution.
Floating-point formatting is now locale-independent by default:
#include <locale> #include <fmt/core.h> int main() { std::locale::global(std::locale("ru_RU.UTF-8")); fmt::print("value = {}", 4.2); }
prints "value = 4.2" regardless of the locale.
For locale-specific formatting use the
n
specifier:std::locale::global(std::locale("ru_RU.UTF-8")); fmt::print("value = {:n}", 4.2);
prints "value = 4,2".
Added an experimental Grisu floating-point formatting algorithm implementation (disabled by default). To enable it compile with the
FMT_USE_GRISU
macro defined to 1:#define FMT_USE_GRISU 1 #include <fmt/format.h> auto s = fmt::format("{}", 4.2); // formats 4.2 using Grisu
With Grisu enabled, {fmt} is 13x faster than
std::ostringstream
(libc++) and 10x faster thansprintf
on dtoa-benchmark (full results):Separated formatting and parsing contexts for consistency with C++20 std::format, removing the undocumented
basic_format_context::parse_context()
function.Added oss-fuzz support (#1199). Thanks @pauldreik (Paul Dreik).
formatter
specializations now always take precedence overoperator<<
(#952):#include <iostream> #include <fmt/ostream.h> struct S {}; std::ostream& operator<<(std::ostream& os, S) { return os << 1; } template <> struct fmt::formatter<S> : fmt::formatter<int> { auto format(S, format_context& ctx) { return formatter<int>::format(2, ctx); } }; int main() { std::cout << S() << "\n"; // prints 1 using operator<< fmt::print("{}\n", S()); // prints 2 using formatter }
Introduced the experimental
fmt::compile
function that does format string compilation (#618, #1169, #1171):#include <fmt/compile.h> auto f = fmt::compile<int>("{}"); std::string s = fmt::format(f, 42); // can be called multiple times to // format different values // s == "42"
It moves the cost of parsing a format string outside of the format function which can be beneficial when identically formatting many objects of the same types. Thanks @stryku (Mateusz Janek).
Added experimental
%
format specifier that formats floating-point values as percentages (#1060, #1069, #1071):auto s = fmt::format("{:.1%}", 0.42); // s == "42.0%"
Thanks @gawain-bolton (Gawain Bolton).
Implemented precision for floating-point durations (#1004, #1012):
auto s = fmt::format("{:.1}", std::chrono::duration<double>(1.234)); // s == 1.2s
Thanks @DanielaE (Daniela Engert).
Implemented
chrono
format specifiers%Q
and%q
that give the value and the unit respectively (#1019):auto value = fmt::format("{:%Q}", 42s); // value == "42" auto unit = fmt::format("{:%q}", 42s); // unit == "s"
Thanks @DanielaE (Daniela Engert).
Fixed handling of dynamic width in chrono formatter:
auto s = fmt::format("{0:{1}%H:%M:%S}", std::chrono::seconds(12345), 12); // ^ width argument index ^ width // s == "03:25:45 "
Thanks Howard Hinnant.
Removed deprecated
fmt/time.h
. Usefmt/chrono.h
instead.Added
fmt::format
andfmt::vformat
overloads that taketext_style
(#993, #994):#include <fmt/color.h> std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), "The answer is {}.", 42);
Thanks @Naios (Denis Blank).
Removed the deprecated color API (
print_colored
). Use the new API, namelyprint
overloads that taketext_style
instead.Made
std::unique_ptr
andstd::shared_ptr
formattable as pointers viafmt::ptr
(#1121):std::unique_ptr<int> p = ...; fmt::print("{}", fmt::ptr(p)); // prints p as a pointer
Thanks @sighingnow (Tao He).
Made
print
andvprint
report I/O errors (#1098, #1099). Thanks @BillyDonahue (Billy Donahue).Marked deprecated APIs with the
[[deprecated]]
attribute and removed internal uses of deprecated APIs (#1022). Thanks @eliaskosunen (Elias Kosunen).Modernized the codebase using more C++11 features and removing workarounds. Most importantly,
buffer_context
is now an alias template, so usebuffer_context<T>
instead ofbuffer_context<T>::type
. These features require GCC 4.8 or later.formatter
specializations now always take precedence over implicit conversions toint
and the undocumentedconvert_to_int
trait is now deprecated.Moved the undocumented
basic_writer
,writer
, andwwriter
types to theinternal
namespace.Removed deprecated
basic_format_context::begin()
. Useout()
instead.Disallowed passing the result of
join
as an lvalue to prevent misuse.Refactored the undocumented structs that represent parsed format specifiers to simplify the API and allow multibyte fill.
Moved SFINAE to template parameters to reduce symbol sizes.
Switched to
fputws
for writing wide strings so that it's no longer required to call_setmode
on Windows (#1229, #1243). Thanks @jackoalan (Jack Andersen).Improved literal-based API (#1254). Thanks @sylveon (Charles Milette).
Added support for exotic platforms without
uintptr_t
such as IBM i (AS/400) which has 128-bit pointers and only 64-bit integers (#1059).Added Sublime Text syntax highlighting config (#1037). Thanks @Kronuz (Germán Méndez Bravo).
Added the
FMT_ENFORCE_COMPILE_STRING
macro to enforce the use of compile-time format strings (#1231). Thanks @jackoalan (Jack Andersen).Stopped setting
CMAKE_BUILD_TYPE
if {fmt} is a subproject (#1081).Various build improvements (#1039, #1078, #1091, #1103, #1177). Thanks @luncliff (Park DongHa), @jasonszang (Jason Shuo Zang), @olafhering (Olaf Hering), @Lecetem, @pauldreik (Paul Dreik).
Improved documentation (#1049, #1051, #1083, #1113, #1114, #1146, #1180, #1250, #1252, #1265). Thanks @mikelui (Michael Lui), @foonathan (Jonathan Müller), @BillyDonahue (Billy Donahue), @jwakely (Jonathan Wakely), @kaisbe (Kais Ben Salah), @sdebionne (Samuel Debionne).
Fixed ambiguous formatter specialization in
fmt/ranges.h
(#1123).Fixed formatting of a non-empty
std::filesystem::path
which is an infinitely deep range of its components (#1268).Fixed handling of general output iterators when formatting characters (#1056, #1058). Thanks @abolz (Alexander Bolz).
Fixed handling of output iterators in
formatter
specialization for ranges (#1064).Fixed handling of exotic character types (#1188).
Made chrono formatting work with exceptions disabled (#1062).
Fixed DLL visibility issues (#1134, #1147). Thanks @denchat.
Disabled the use of UDL template extension on GCC 9 (#1148).
Removed misplaced
format
compile-time checks fromprintf
(#1173).Fixed issues in the experimental floating-point formatter (#1072, #1129, #1153, #1155, #1210, #1222). Thanks @alabuzhev (Alex Alabuzhev).
Fixed bugs discovered by fuzzing or during fuzzing integration (#1124, #1127, #1132, #1135, #1136, #1141, #1142, #1178, #1179, #1194). Thanks @pauldreik (Paul Dreik).
Fixed building tests on FreeBSD and Hurd (#1043). Thanks @jackyf (Eugene V. Lyubimkin).
Fixed various warnings and compilation issues (#998, #1006, #1008, #1011, #1025, #1027, #1028, #1029, #1030, #1031, #1054, #1063, #1068, #1074, #1075, #1079, #1086, #1088, #1089, #1094, #1101, #1102, #1105, #1107, #1115, #1117, #1118, #1120, #1123, #1139, #1140, #1143, #1144, #1150, #1151, #1152, #1154, #1156, #1159, #1175, #1181, #1186, #1187, #1191, #1197, #1200, #1203, #1205, #1206, #1213, #1214, #1217, #1228, #1230, #1232, #1235, #1236, #1240). Thanks @DanielaE (Daniela Engert), @mwinterb, @eliaskosunen (Elias Kosunen), @morinmorin, @ricco19 (Brian Ricciardelli), @waywardmonkeys (Bruce Mitchener), @chronoxor (Ivan Shynkarenka), @remyabel, @pauldreik (Paul Dreik), @gsjaardema (Greg Sjaardema), @rcane (Ronny Krüger), @mocabe, @denchat, @cjdb (Christopher Di Bella), @HazardyKnusperkeks (Björn Schäpers), @vedranmiletic (Vedran Miletić), @jackoalan (Jack Andersen), @DaanDeMeyer (Daan De Meyer), @starkmapper (Mark Stapper).
Introduced experimental chrono formatting support:
#include <fmt/chrono.h> int main() { using namespace std::literals::chrono_literals; fmt::print("Default format: {} {}\n", 42s, 100ms); fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s); }
prints:
Default format: 42s 100ms strftime-like format: 03:15:30
Added experimental support for emphasis (bold, italic, underline, strikethrough), colored output to a file stream, and improved colored formatting API (#961, #967, #973):
#include <fmt/color.h> int main() { print(fg(fmt::color::crimson) | fmt::emphasis::bold, "Hello, {}!\n", "world"); print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | fmt::emphasis::underline, "Hello, {}!\n", "мир"); print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, "Hello, {}!\n", "世界"); }
prints the following on modern terminals with RGB color support:
Thanks @Rakete1111 (Nicolas).
Added support for 4-bit terminal colors (#968, #974)
#include <fmt/color.h> int main() { print(fg(fmt::terminal_color::red), "stop\n"); }
Note that these colors vary by terminal:
Thanks @Rakete1111 (Nicolas).
Parameterized formatting functions on the type of the format string (#880, #881, #883, #885, #897, #920). Any object of type
S
that has an overloadedto_string_view(const S&)
returningfmt::string_view
can be used as a format string: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);
Thanks @DanielaE (Daniela Engert).
Made
std::string_view
work as a format string (#898):auto message = fmt::format(std::string_view("The answer is {}."), 42);
Thanks @DanielaE (Daniela Engert).
Added wide string support to compile-time format string checks (#924):
print(fmt(L"{:f}"), 42); // compile-time error: invalid type specifier
Thanks @XZiar.
Made colored print functions work with wide strings (#867):
#include <fmt/color.h> int main() { print(fg(fmt::color::red), L"{}\n", 42); }
Thanks @DanielaE (Daniela Engert).
Introduced experimental Unicode support (#628, #891):
using namespace fmt::literals; auto s = fmt::format("{:*^5}"_u, "🤡"_u); // s == "**🤡**"_u
Improved locale support:
#include <fmt/locale.h> struct numpunct : std::numpunct<char> { protected: char do_thousands_sep() const override { return '~'; } }; std::locale loc; auto s = fmt::format(std::locale(loc, new numpunct()), "{:n}", 1234567); // s == "1~234~567"
Constrained formatting functions on proper iterator types (#921). Thanks @DanielaE (Daniela Engert).
Added
make_printf_args
andmake_wprintf_args
functions (#934). Thanks @tnovotny.Deprecated
fmt::visit
,parse_context
, andwparse_context
. Usefmt::visit_format_arg
,format_parse_context
, andwformat_parse_context
instead.Removed undocumented
basic_fixed_buffer
which has been superseded by the iterator-based API (#873, #902). Thanks @superfunc (hollywood programmer).Disallowed repeated leading zeros in an argument ID:
fmt::print("{000}", 42); // error
Reintroduced support for gcc 4.4.
Fixed compilation on platforms with exotic
double
(#878).Improved documentation (#164, #877, #901, #906, #979). Thanks @kookjr (Mathew Cucuzella), @DarkDimius (Dmitry Petrashko), @HecticSerenity.
Added pkgconfig support which makes it easier to consume the library from meson and other build systems (#916). Thanks @colemickens (Cole Mickens).
Various build improvements (#909, #926, #937, #953, #959). Thanks @tchaikov (Kefu Chai), @luncliff (Park DongHa), @AndreasSchoenle (Andreas Schönle), @hotwatermorning, @Zefz (JohanJansen).
Improved
string_view
construction performance (#914). Thanks @gabime (Gabi Melman).Fixed non-matching char types (#895). Thanks @DanielaE (Daniela Engert).
Fixed
format_to_n
withstd::back_insert_iterator
(#913). Thanks @DanielaE (Daniela Engert).Fixed locale-dependent formatting (#905).
Fixed various compiler warnings and errors (#882, #886, #933, #941, #931, #943, #954, #956, #962, #965, #977, #983, #989). Thanks @Luthaf (Guillaume Fraux), @stevenhoving (Steven Hoving), @christinaa (Kristina Brooks), @lgritz (Larry Gritz), @DanielaE (Daniela Engert), @0x8000-0000 (Sign Bit), @liuping1997.
- Fixed
visit
lookup issues on gcc 7 & 8 (#870). Thanks @medithe. - Fixed linkage errors on older gcc.
- Prevented
fmt/range.h
from specializingfmt::basic_string_view
(#865, #868). Thanks @hhggit (dual). - Improved error message when formatting unknown types (#872). Thanks @foonathan (Jonathan Müller),
- Disabled templated user-defined literals when compiled under nvcc (#875). Thanks @CandyGumdrop (Candy Gumdrop),
- Fixed
format_to
formatting towmemory_buffer
(#874).
Optimized format string parsing and argument processing which resulted in up to 5x speed up on long format strings and significant performance boost on various benchmarks. For example, version 5.2 is 2.22x faster than 5.1 on decimal integer formatting with
format_to
(macOS, clang-902.0.39.2):Method
Time, s
Speedup
fmt::format 5.1
0.58
fmt::format 5.2
0.35
1.66x
fmt::format_to 5.1
0.51
fmt::format_to 5.2
0.23
2.22x
sprintf
0.71
std::to_string
1.01
std::stringstream
1.73
Changed the
fmt
macro from opt-out to opt-in to prevent name collisions. To enable it define theFMT_STRING_ALIAS
macro to 1 before includingfmt/format.h
:#define FMT_STRING_ALIAS 1 #include <fmt/format.h> std::string answer = format(fmt("{}"), 42);
Added compile-time format string checks to
format_to
overload that takesfmt::memory_buffer
(#783):fmt::memory_buffer buf; // Compile-time error: invalid type specifier. fmt::format_to(buf, fmt("{:d}"), "foo");
Moved experimental color support to
fmt/color.h
and enabled the new API by default. The old API can be enabled by defining theFMT_DEPRECATED_COLORS
macro.Added formatting support for types explicitly convertible to
fmt::string_view
:struct foo { explicit operator fmt::string_view() const { return "foo"; } }; auto s = format("{}", foo());
In particular, this makes formatting function work with
folly::StringPiece
.Implemented preliminary support for
char*_t
by replacing theformat
function overloads with a single function template parameterized on the string type.Added support for dynamic argument lists (#814, #819). Thanks @MikePopoloski (Michael Popoloski).
Reduced executable size overhead for embedded targets using newlib nano by making locale dependency optional (#839). Thanks @teajay-fr (Thomas Benard).
Keep
noexcept
specifier when exceptions are disabled (#801, #810). Thanks @qis (Alexej Harm).Fixed formatting of user-defined types providing
operator<<
withformat_to_n
(#806). Thanks @mkurdej (Marek Kurdej).Fixed dynamic linkage of new symbols (#808).
Fixed global initialization issue (#807):
// This works on compilers with constexpr support. static const std::string answer = fmt::format("{}", 42);
Fixed various compiler warnings and errors (#804, #809, #811, #822, #827, #830, #838, #843, #844, #851, #852, #854). Thanks @henryiii (Henry Schreiner), @medithe, and @eliasdaler (Elias Daler).
Added experimental support for RGB color output enabled with the
FMT_EXTENDED_COLORS
macro:#define FMT_EXTENDED_COLORS #define FMT_HEADER_ONLY // or compile fmt with FMT_EXTENDED_COLORS defined #include <fmt/format.h> fmt::print(fmt::color::steel_blue, "Some beautiful text");
The old API (the
print_colored
andvprint_colored
functions and thecolor
enum) is now deprecated. (#762 #767). thanks @Remotion (Remo).Added quotes to strings in ranges and tuples (#766). Thanks @Remotion (Remo).
Made
format_to
work withbasic_memory_buffer
(#776).Added
vformat_to_n
andwchar_t
overload offormat_to_n
(#764, #769).Made
is_range
andis_tuple_like
part of public (experimental) API to allow specialization for user-defined types (#751, #759). Thanks @drrlvn (Dror Levin).Added more compilers to continuous integration and increased
FMT_PEDANTIC
warning levels (#736). Thanks @eliaskosunen (Elias Kosunen).Fixed compilation with MSVC 2013.
Fixed handling of user-defined types in
format_to
(#793).Forced linking of inline
vformat
functions into the library (#795).Fixed incorrect call to on_align in
'{:}='
(#750).Fixed floating-point formatting to a non-back_insert_iterator with sign & numeric alignment specified (#756).
Fixed formatting to an array with
format_to_n
(#778).Fixed formatting of more than 15 named arguments (#754).
Fixed handling of compile-time strings when including
fmt/ostream.h
. (#768).Fixed various compiler warnings and errors (#742, #748, #752, #770, #775, #779, #780, #790, #792, #800). Thanks @Remotion (Remo), @gabime (Gabi Melman), @foonathan (Jonathan Müller), @Dark-Passenger (Dhruv Paranjape), and @0x8000-0000 (Sign Bit).
Added a requirement for partial C++11 support, most importantly variadic templates and type traits, and dropped
FMT_VARIADIC_*
emulation macros. Variadic templates are available since GCC 4.4, Clang 2.9 and MSVC 18.0 (2013). For older compilers use {fmt} version 4.x which continues to be maintained and works with C++98 compilers.Renamed symbols to follow standard C++ naming conventions and proposed a subset of the library for standardization in P0645R2 Text Formatting.
Implemented
constexpr
parsing of format strings and compile-time format string checks. For example#include <fmt/format.h> std::string s = format(fmt("{:d}"), "foo");
gives a compile-time error because
d
is an invalid specifier for strings (godbolt):... <source>:4:19: note: in instantiation of function template specialization 'fmt::v5::format<S, char [4]>' requested here std::string s = format(fmt("{:d}"), "foo"); ^ format.h:1337:13: note: non-constexpr function 'on_error' cannot be used in a constant expression handler.on_error("invalid type specifier");
Compile-time checks require relaxed
constexpr
(C++14 feature) support. If the latter is not available, checks will be performed at runtime.Separated format string parsing and formatting in the extension API to enable compile-time format string processing. For example
struct Answer {}; namespace fmt { template <> struct formatter<Answer> { constexpr auto parse(parse_context& ctx) { auto it = ctx.begin(); spec = *it; if (spec != 'd' && spec != 's') throw format_error("invalid specifier"); return ++it; } template <typename FormatContext> auto format(Answer, FormatContext& ctx) { return spec == 's' ? format_to(ctx.begin(), "{}", "fourty-two") : format_to(ctx.begin(), "{}", 42); } char spec = 0; }; } std::string s = format(fmt("{:x}"), Answer());
gives a compile-time error due to invalid format specifier (godbolt):
... <source>:12:45: error: expression '<throw-expression>' is not a constant expression throw format_error("invalid specifier");
Added iterator support:
#include <vector> #include <fmt/format.h> std::vector<char> out; fmt::format_to(std::back_inserter(out), "{}", 42);
Added the format_to_n function that restricts the output to the specified number of characters (#298):
char out[4]; fmt::format_to_n(out, sizeof(out), "{}", 12345); // out == "1234" (without terminating '\0')
Added the formatted_size function for computing the output size:
#include <fmt/format.h> auto size = fmt::formatted_size("{}", 12345); // size == 5
Improved compile times by reducing dependencies on standard headers and providing a lightweight core API:
#include <fmt/core.h> fmt::print("The answer is {}.", 42);
Added the make_format_args function for capturing formatting arguments:
// Prints formatted error message. void vreport_error(const char *format, fmt::format_args args) { fmt::print("Error: "); fmt::vprint(format, args); } template <typename... Args> void report_error(const char *format, const Args & ... args) { vreport_error(format, fmt::make_format_args(args...)); }
Added the
make_printf_args
function for capturingprintf
arguments (#687, #694). Thanks @Kronuz (Germán Méndez Bravo).Added prefix
v
to non-variadic functions takingformat_args
to distinguish them from variadic ones:std::string vformat(string_view format_str, format_args args); template <typename... Args> std::string format(string_view format_str, const Args & ... args);
Added experimental support for formatting ranges, containers and tuple-like types in
fmt/ranges.h
(#735):#include <fmt/ranges.h> std::vector<int> v = {1, 2, 3}; fmt::print("{}", v); // prints {1, 2, 3}
Thanks @Remotion (Remo).
Implemented
wchar_t
date and time formatting (#712):#include <fmt/time.h> std::time_t t = std::time(nullptr); auto s = fmt::format(L"The date is {:%Y-%m-%d}.", *std::localtime(&t));
Thanks @DanielaE (Daniela Engert).
Provided more wide string overloads (#724). Thanks @DanielaE (Daniela Engert).
Switched from a custom null-terminated string view class to
string_view
in the format API and providedfmt::string_view
which implements a subset ofstd::string_view
API for pre-C++17 systems.Added support for
std::experimental::string_view
(#607):#include <fmt/core.h> #include <experimental/string_view> fmt::print("{}", std::experimental::string_view("foo"));
Allowed mixing named and automatic arguments:
fmt::format("{} {two}", 1, fmt::arg("two", 2));
Removed the write API in favor of the format API with compile-time handling of format strings.
Disallowed formatting of multibyte strings into a wide character target (#606).
Improved documentation (#515, #614, #617, #661, #680). Thanks @ibell (Ian Bell), @mihaitodor (Mihai Todor), and @johnthagen.
Implemented more efficient handling of large number of format arguments.
Introduced an inline namespace for symbol versioning.
Added debug postfix
d
to thefmt
library name (#636).Removed unnecessary
fmt/
prefix in includes (#397). Thanks @chronoxor (Ivan Shynkarenka).Moved
fmt/*.h
toinclude/fmt/*.h
to prevent irrelevant files and directories appearing on the include search paths when fmt is used as a subproject and moved source files to thesrc
directory.Added qmake project file
support/fmt.pro
(#641). Thanks @cowo78 (Giuseppe Corbelli).Added Gradle build file
support/build.gradle
(#649). Thanks @luncliff (Park DongHa).Removed
FMT_CPPFORMAT
CMake option.Fixed a name conflict with the macro
CHAR_WIDTH
in glibc (#616). Thanks @aroig (Abdó Roig-Maranges).Fixed handling of nested braces in
fmt::join
(#638).Added
SOURCELINK_SUFFIX
for compatibility with Sphinx 1.5 (#497). Thanks @ginggs (Graham Inggs).Added a missing
inline
in the header-only mode (#626). Thanks @aroig (Abdó Roig-Maranges).Fixed various compiler warnings (#640, #656, #679, #681, #705, #715, #717, #720, #723, #726, #730, #739). Thanks @peterbell10, @LarsGullik, @foonathan (Jonathan Müller), @eliaskosunen (Elias Kosunen), @christianparpart (Christian Parpart), @DanielaE (Daniela Engert), and @mwinterb.
Worked around an MSVC bug and fixed several warnings (#653). Thanks @alabuzhev (Alex Alabuzhev).
Worked around GCC bug 67371 (#682).
Fixed compilation with
-fno-exceptions
(#655). Thanks @chenxiaolong (Andrew Gunnerson).Made
constexpr remove_prefix
gcc version check tighter (#648).Renamed internal type enum constants to prevent collision with poorly written C libraries (#644).
Added detection of
wostream operator<<
(#650).Fixed compilation when there is a mismatch between
-std
options between the library and user code (#664).Fixed compilation with GCC 7 and
-std=c++11
(#734).Improved generated binary code on GCC 7 and older (#668).
Fixed handling of numeric alignment with no width (#675).
Fixed handling of empty strings in UTF8/16 converters (#676). Thanks @vgalka-sl (Vasili Galka).
Fixed formatting of an empty
string_view
(#689).Fixed detection of
string_view
on libc++ (#686).Fixed DLL issues (#696). Thanks @sebkoenig.
Fixed compile checks for mixing narrow and wide strings (#690).
Disabled unsafe implicit conversion to
std::string
(#729).Fixed handling of reused format specs (as in
fmt::join
) for pointers (#725). Thanks @mwinterb.
- Added
fmt::to_wstring()
in addition tofmt::to_string()
(#559). Thanks @alabuzhev (Alex Alabuzhev). - Added support for C++17
std::string_view
(#571 and #578). Thanks @thelostt (Mário Feroldi) and @mwinterb. - Enabled stream exceptions to catch errors (#581). Thanks @crusader-mike.
- Allowed formatting of class hierarchies with
fmt::format_arg()
(#547). Thanks @rollbear (Björn Fahller). - Removed limitations on character types (#563). Thanks @Yelnats321 (Elnar Dakeshov).
- Conditionally enabled use of
std::allocator_traits
(#583). Thanks @mwinterb. - Added support for
const
variadic member function emulation withFMT_VARIADIC_CONST
(#591). Thanks @ludekvodicka (Ludek Vodicka). - Various bugfixes: bad overflow check, unsupported implicit type conversion when determining formatting function, test segfaults (#551), ill-formed macros (#542) and ambiguous overloads (#580). Thanks @xylosper (Byoung-young Lee).
- Prevented warnings on MSVC (#605,
#602, and
#545),
clang (#582),
GCC (#573),
various conversion warnings (#609,
#567,
#553 and
#553), and added
override
and[[noreturn]]
(#549 and #555). Thanks @alabuzhev (Alex Alabuzhev), @virgiliofornazin (Virgilio Alexandre Fornazin), @alexanderbock (Alexander Bock), @yumetodo, @VaderY (Császár Mátyás), @jpcima (JP Cimalando), @thelostt (Mário Feroldi), and @Manu343726 (Manu Sánchez). - Improved CMake: Used
GNUInstallDirs
to set installation location (#610) and fixed warnings (#536 and #556). Thanks @mikecrowe (Mike Crowe), @evgen231 and @henryiii (Henry Schreiner).
Removed old compatibility headers
cppformat/*.h
and CMake options (#527). Thanks @maddinat0r (Alex Martin).Added
string.h
containingfmt::to_string()
as alternative tostd::to_string()
as well as other string writer functionality (#326 and #441):#include "fmt/string.h" std::string answer = fmt::to_string(42);
Thanks to @glebov-andrey (Andrey Glebov).
Moved
fmt::printf()
to newprintf.h
header and allowed%s
as generic specifier (#453), made%.f
more conformant to regularprintf()
(#490), added custom writer support (#476) and implemented missing custom argument formatting (#339 and #340):#include "fmt/printf.h" // %s format specifier can be used with any argument type. fmt::printf("%s", 42);
Thanks @mojoBrendan, @manylegged (Arthur Danskin) and @spacemoose (Glen Stark). See also #360, #335 and #331.
Added
container.h
containing aBasicContainerWriter
to write to containers likestd::vector
(#450). Thanks @polyvertex (Jean-Charles Lefebvre).Added
fmt::join()
function that takes a range and formats its elements separated by a given string (#466):#include "fmt/format.h" std::vector<double> v = {1.2, 3.4, 5.6}; // Prints "(+01.20, +03.40, +05.60)". fmt::print("({:+06.2f})", fmt::join(v.begin(), v.end(), ", "));
Thanks @olivier80.
Added support for custom formatting specifications to simplify customization of built-in formatting (#444). Thanks @polyvertex (Jean-Charles Lefebvre). See also #439.
Added
fmt::format_system_error()
for error code formatting (#323 and #526). Thanks @maddinat0r (Alex Martin).Added thread-safe
fmt::localtime()
andfmt::gmtime()
as replacement for the standard version totime.h
(#396). Thanks @codicodi.Internal improvements to
NamedArg
andArgLists
(#389 and #390). Thanks @chronoxor.Fixed crash due to bug in
FormatBuf
(#493). Thanks @effzeh. See also #480 and #491.Fixed handling of wide strings in
fmt::StringWriter
.Improved compiler error messages (#357).
Fixed various warnings and issues with various compilers (#494, #499, #483, #485, #482, #475, #473 and #414). Thanks @chronoxor, @zhaohuaxishi, @pkestene (Pierre Kestener), @dschmidt (Dominik Schmidt) and @0x414c (Alexey Gorishny) .
Improved CMake: targets are now namespaced (#511 and #513), supported header-only
printf.h
(#354), fixed issue with minimal supported library subset (#418, #419 and #420). Thanks @bjoernthiel (Bjoern Thiel), @niosHD (Mario Werner), @LogicalKnight (Sean LK) and @alabuzhev (Alex Alabuzhev).Improved documentation. Thanks to @pwm1234 (Phil) for #393.
- Added
FMT_VERSION
macro (#411). - Used
FMT_NULL
instead of literal0
(#409). Thanks @alabuzhev (Alex Alabuzhev). - Added extern templates for
format_float
(#413). - Fixed implicit conversion issue (#507).
- Fixed signbit detection (#423).
- Fixed naming collision (#425).
- Fixed missing intrinsic for C++/CLI (#457). Thanks @calumr (Calum Robinson)
- Fixed Android detection (#458). Thanks @Gachapen (Magnus Bjerke Vik).
- Use lean
windows.h
if not in header-only mode (#503). Thanks @Quentin01 (Quentin Buathier). - Fixed issue with CMake exporting C++11 flag (#445). Thanks @EricWF (Eric).
- Fixed issue with nvcc and MSVC compiler bug and MinGW (#505).
- Fixed DLL issues (#469 and #502). Thanks @richardeakin (Richard Eakin) and @AndreasSchoenle (Andreas Schönle).
- Fixed test compilation under FreeBSD (#433).
- Fixed various warnings (#403, #410 and #510). Thanks @Lecetem, @chenhayat (Chen Hayat) and @trozen.
- Worked around a broken
__builtin_clz
in clang with MS codegen (#519). - Removed redundant include (#479).
- Fixed documentation issues.
- Fixed handling of thousands separator (#353).
- Fixed handling of
unsigned char
strings (#373). - Corrected buffer growth when formatting time (#367).
- Removed warnings under MSVC and clang (#318, #250, also merged #385 and #361). Thanks @jcelerier (Jean-Michaël Celerier) and @nmoehrle (Nils Moehrle).
- Fixed compilation issues under Android (#327, #345 and #381), FreeBSD (#358), Cygwin (#388), MinGW (#355) as well as other issues (#350, #366, #348, #402, #405). Thanks to @dpantele (Dmitry), @hghwng (Hugh Wang), @arvedarved (Tilman Keskinöz), @LogicalKnight (Sean) and @JanHellwig (Jan Hellwig).
- Fixed some documentation issues and extended specification (#320, #333, #347, #362). Thanks to @smellman (Taro Matsuzawa aka. btm).
The project has been renamed from C++ Format (cppformat) to fmt for consistency with the used namespace and macro prefix (#307). Library headers are now located in the
fmt
directory:#include "fmt/format.h"
Including
format.h
from thecppformat
directory is deprecated but works via a proxy header which will be removed in the next major version.The documentation is now available at https://fmt.dev.
Added support for strftime-like date and time formatting (#283):
#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));
std::ostream
support including formatting of user-defined types that provide overloadedoperator<<
has been moved tofmt/ostream.h
:#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"
Added support for custom argument formatters (#235).
Added support for locale-specific integer formatting with the
n
specifier (#305):std::setlocale(LC_ALL, "en_US.utf8"); fmt::print("cppformat: {:n}\n", 1234567); // prints 1,234,567
Sign is now preserved when formatting an integer with an incorrect
printf
format specifier (#265):fmt::printf("%lld", -42); // prints -42
Note that it would be an undefined behavior in
std::printf
.Length modifiers such as
ll
are now optional in printf formatting functions and the correct type is determined automatically (#255):fmt::printf("%d", std::numeric_limits<long long>::max());
Note that it would be an undefined behavior in
std::printf
.Added initial support for custom formatters (#231).
Fixed detection of user-defined literal support on Intel C++ compiler (#311, #312). Thanks to @dean0x7d (Dean Moldovan) and @speth (Ray Speth).
Reduced compile time (#243, #249, #317):
Thanks to @dean0x7d (Dean Moldovan).
Compile test fixes (#313). Thanks to @dean0x7d (Dean Moldovan).
Documentation fixes (#239, #248, #252, #258, #260, #301, #309). Thanks to @ReadmeCritic @Gachapen (Magnus Bjerke Vik) and @jwilk (Jakub Wilk).
Fixed compiler and sanitizer warnings (#244, #256, #259, #263, #274, #277, #286, #291, #296, #308) Thanks to @mwinterb, @pweiskircher (Patrik Weiskircher), @Naios.
Improved compatibility with Windows Store apps (#280, #285) Thanks to @mwinterb.
Added tests of compatibility with older C++ standards (#273). Thanks to @niosHD.
Changed
ArgMap
to be backed by a vector instead of a map. (#261, #262). Thanks to @mwinterb.Added
fprintf
overload that writes to astd::ostream
(#251). Thanks to nickhutchinson (Nicholas Hutchinson).Export symbols when building a Windows DLL (#245). Thanks to macdems (Maciek Dems).
Fixed compilation on Cygwin (#304).
Implemented a workaround for a bug in Apple LLVM version 4.2 of clang (#276).
Implemented a workaround for Google Test bug #705 on gcc 6 (#268). Thanks to octoploid.
Removed Biicode support because the latter has been discontinued.
- The install location for generated CMake files is now configurable via
the
FMT_CMAKE_DIR
CMake variable (#299). Thanks to @niosHD. - Documentation fixes (#252).
Project layout and build system improvements (#267):
- The code have been moved to the
cppformat
directory. Includingformat.h
from the top-level directory is deprecated but works via a proxy header which will be removed in the next major version. - C++ Format CMake targets now have proper interface definitions.
- Installed version of the library now supports the header-only configuration.
- Targets
doc
,install
, andtest
are now disabled if C++ Format is included as a CMake subproject. They can be enabled by settingFMT_DOC
,FMT_INSTALL
, andFMT_TEST
in the parent project.
Thanks to @niosHD.
- The code have been moved to the
- Improved CMake find and package support (#264). Thanks to @niosHD.
- Fix compile error with Android NDK and mingw32 (#241). Thanks to @Gachapen (Magnus Bjerke Vik).
- Documentation fixes (#248, #260).
[Breaking] Named arguments (#169, #173, #174):
fmt::print("The answer is {answer}.", fmt::arg("answer", 42));
Thanks to @jamboree.
[Experimental] User-defined literals for format and named arguments (#204, #206, #207):
using namespace fmt::literals; fmt::print("The answer is {answer}.", "answer"_a=42);
Thanks to @dean0x7d (Dean Moldovan).
[Breaking] Formatting of more than 16 arguments is now supported when using variadic templates (#141). Thanks to @Shauren.
Runtime width specification (#168):
fmt::format("{0:{1}}", 42, 5); // gives " 42"
Thanks to @jamboree.
[Breaking] Enums are now formatted with an overloaded
std::ostream
insertion operator (operator<<
) if available (#232).[Breaking] Changed default
bool
format to textual, "true" or "false" (#170):fmt::print("{}", true); // prints "true"
To print
bool
as a number use numeric format specifier such asd
:fmt::print("{:d}", true); // prints "1"
fmt::printf
andfmt::sprintf
now support formatting ofbool
with the%s
specifier giving textual output, "true" or "false" (#223):fmt::printf("%s", true); // prints "true"
Thanks to @LarsGullik.
[Breaking]
signed char
andunsigned char
are now formatted as integers by default (#217).[Breaking] Pointers to C strings can now be formatted with the
p
specifier (#223):fmt::print("{:p}", "test"); // prints pointer value
Thanks to @LarsGullik.
[Breaking]
fmt::printf
andfmt::sprintf
now print null pointers as(nil)
and null strings as(null)
for consistency with glibc (#226). Thanks to @LarsGullik.[Breaking]
fmt::(s)printf
now supports formatting of objects of user-defined types that provide an overloadedstd::ostream
insertion operator (operator<<
) (#201):fmt::printf("The date is %s", Date(2012, 12, 9));
[Breaking] The
Buffer
template is now part of the public API and can be used to implement custom memory buffers (#140). Thanks to @polyvertex (Jean-Charles Lefebvre).[Breaking] Improved compatibility between
BasicStringRef
and std::experimental::basic_string_view (#100, #159, #183):- Comparison operators now compare string content, not pointers
BasicStringRef::c_str
replaced byBasicStringRef::data
BasicStringRef
is no longer assumed to be null-terminated
References to null-terminated strings are now represented by a new class,
BasicCStringRef
.Dependency on pthreads introduced by Google Test is now optional (#185).
New CMake options
FMT_DOC
,FMT_INSTALL
andFMT_TEST
to control generation ofdoc
,install
andtest
targets respectively, on by default (#197, #198, #200). Thanks to @maddinat0r (Alex Martin).noexcept
is now used when compiling with MSVC2015 (#215). Thanks to @dmkrepo (Dmitriy).Added an option to disable use of
windows.h
whenFMT_USE_WINDOWS_H
is defined as 0 before includingformat.h
(#171). Thanks to @alfps (Alf P. Steinbach).[Breaking]
windows.h
is now included withNOMINMAX
unlessFMT_WIN_MINMAX
is defined. This is done to prevent breaking code usingstd::min
andstd::max
and only affects the header-only configuration (#152, #153, #154). Thanks to @DevO2012.Improved support for custom character types (#171). Thanks to @alfps (Alf P. Steinbach).
Added an option to disable use of IOStreams when
FMT_USE_IOSTREAMS
is defined as 0 before includingformat.h
(#205, #208). Thanks to @JodiTheTigger.Improved detection of
isnan
,isinf
andsignbit
.
- Made formatting of user-defined types more efficient with a custom stream buffer (#92, #230). Thanks to @NotImplemented.
- Further improved performance of
fmt::Writer
on integer formatting and fixed a minor regression. Now it is ~7% faster thankarma::generate
on Karma's benchmark (#186). - [Breaking] Reduced compiled code size (#143, #149).
[Breaking] Headers are now installed in
${CMAKE_INSTALL_PREFIX}/include/cppformat
(#178). Thanks to @jackyf (Eugene V. Lyubimkin).[Breaking] Changed the library name from
format
tocppformat
for consistency with the project name and to avoid potential conflicts (#178). Thanks to @jackyf (Eugene V. Lyubimkin).C++ Format is now available in Debian GNU/Linux (stretch, sid) and derived distributions such as Ubuntu 15.10 and later (#155):
$ sudo apt-get install libcppformat1-dev
Thanks to @jackyf (Eugene V. Lyubimkin).
Packages for Fedora and RHEL are now available. Thanks to Dave Johansen.
C++ Format can now be installed via Homebrew on OS X (#157):
$ brew install cppformat
Thanks to @ortho, Anatoliy Bulukin.
- Migrated from ReadTheDocs to GitHub Pages for better responsiveness and reliability (#128). New documentation address is http://cppformat.github.io/.
- Added Building the documentation section to the documentation.
- Documentation build script is now compatible with Python 3 and newer pip versions. (#189, #209). Thanks to @JodiTheTigger and @xentec.
- Documentation fixes and improvements (#36, #75, #125, #160, #161, #162, #165, #210). Thanks to @syohex (Syohei YOSHIDA) and bug reporters.
- Fixed out-of-tree documentation build (#177). Thanks to @jackyf (Eugene V. Lyubimkin).
Fixed
initializer_list
detection (#136). Thanks to @Gachapen (Magnus Bjerke Vik).[Breaking] Fixed formatting of enums with numeric format specifiers in
fmt::(s)printf
(#131, #139):enum { ANSWER = 42 }; fmt::printf("%d", ANSWER);
Thanks to @Naios.
Improved compatibility with old versions of MinGW (#129, #130, #132). Thanks to @cstamford (Christopher Stamford).
Fixed a compile error on MSVC with disabled exceptions (#144).
Added a workaround for broken implementation of variadic templates in MSVC2012 (#148).
Placed the anonymous namespace within
fmt
namespace for the header-only configuration (#171). Thanks to @alfps (Alf P. Steinbach).Implemented a workaround for a name lookup bug in MSVC2010 (#188).
Fixed compiler warnings (#95, #96, #114, #135, #142, #145, #146, #158, #163, #175, #190, #191, #194, #196, #216, #218, #220, #229, #233, #234, #236, #281, #289). Thanks to @seanmiddleditch (Sean Middleditch), @dixlorenz (Dix Lorenz), @CarterLi (李通洲), @Naios, @fmatthew5876 (Matthew Fioravante), @LevskiWeng (Levski Weng), @rpopescu, @gabime (Gabi Melman), @cubicool (Jeremy Moles), @jkflying (Julian Kent), @LogicalKnight (Sean L), @inguin (Ingo van Lil) and @Jopie64 (Johan).
Fixed portability issues (mostly causing test failures) on ARM, ppc64, ppc64le, s390x and SunOS 5.11 i386 (#138, #179, #180, #202, #225, Red Hat Bugzilla Bug 1260297). Thanks to @Naios, @jackyf (Eugene V. Lyubimkin) and Dave Johansen.
Fixed a name conflict with macro
free
defined incrtdbg.h
when_CRTDBG_MAP_ALLOC
is set (#211).Fixed shared library build on OS X (#212). Thanks to @dean0x7d (Dean Moldovan).
Fixed an overload conflict on MSVC when
/Zc:wchar_t-
option is specified (#214). Thanks to @slavanap (Vyacheslav Napadovsky).Improved compatibility with MSVC 2008 (#236). Thanks to @Jopie64 (Johan).
Improved compatibility with bcc32 (#227).
Fixed
static_assert
detection on Clang (#228). Thanks to @dean0x7d (Dean Moldovan).
Added
BasicArrayWriter
, a class template that provides operations for formatting and writing data into a fixed-size array (#105 and #122):char buffer[100]; fmt::ArrayWriter w(buffer); w.write("The answer is {}", 42);
Added 0 A.D. and PenUltima Online (POL) to the list of notable projects using C++ Format.
C++ Format now uses MSVC intrinsics for better formatting performance (#115, #116, #118 and #121). Previously these optimizations where only used on GCC and Clang. Thanks to @CarterLi and @objectx.
CMake install target (#119). Thanks to @TrentHouliston.
You can now install C++ Format with
make install
command.Improved Biicode support (#98 and #104). Thanks to @MariadeAnton and @franramirez688.
Improved support for building with Android NDK (#107). Thanks to @newnon.
The android-ndk-example repository provides and example of using C++ Format with Android NDK:
Improved documentation of
SystemError
andWindowsError
(#54).Various code improvements (#110, #111 #112). Thanks to @CarterLi.
Improved compile-time errors when formatting wide into narrow strings (#117).
Fixed
BasicWriter::write
without formatting arguments when C++11 support is disabled (#109).Fixed header-only build on OS X with GCC 4.9 (#124).
Fixed packaging issues (#94).
Add support for a header-only configuration when
FMT_HEADER_ONLY
is defined before includingformat.h
:#define FMT_HEADER_ONLY #include "format.h"
Compute string length in the constructor of
BasicStringRef
instead of thesize
method (#79). This eliminates size computation for string literals on reasonable optimizing compilers.Fix formatting of types with overloaded
operator <<
forstd::wostream
(#86):fmt::format(L"The date is {0}", Date(2012, 12, 9));
Fix linkage of tests on Arch Linux (#89).
Allow precision specifier for non-float arguments (#90):
fmt::print("{:.3}\n", "Carpet"); // prints "Car"
Fix build on Android NDK (#93)
Improvements to documentation build procedure.
Remove
FMT_SHARED
CMake variable in favor of standard BUILD_SHARED_LIBS.Fix error handling in
fmt::fprintf
.Fix a number of warnings.
[Breaking] Improved separation between formatting and buffer management.
Writer
is now a base class that cannot be instantiated directly. The newMemoryWriter
class implements the default buffer management with small allocations done on stack. Sofmt::Writer
should be replaced withfmt::MemoryWriter
in variable declarations.Old code:
fmt::Writer w;
New code:
fmt::MemoryWriter w;
If you pass
fmt::Writer
by reference, you can continue to do so:void f(fmt::Writer &w);
This doesn't affect the formatting API.
Support for custom memory allocators (#69)
Formatting functions now accept signed char and unsigned char strings as arguments (#73):
auto s = format("GLSL version: {}", glGetString(GL_VERSION));
Reduced code bloat. According to the new benchmark results, cppformat is close to
printf
and by the order of magnitude better than Boost Format in terms of compiled code size.Improved appearance of the documentation on mobile by using the Sphinx Bootstrap theme:
Old
New
Safe printf implementation with a POSIX extension for positional arguments:
fmt::printf("Elapsed time: %.2f seconds", 1.23); fmt::printf("%1$s, %3$d %2$s", weekday, month, day);
Arguments of
char
type can now be formatted as integers (Issue #55):fmt::format("0x{0:02X}", 'a');
Deprecated parts of the API removed.
The library is now built and tested on MinGW with Appveyor in addition to existing test platforms Linux/GCC, OS X/Clang, Windows/MSVC.
Improved API
All formatting methods are now implemented as variadic functions instead of using
operator<<
for feeding arbitrary arguments into a temporary formatter object. This works both with C++11 where variadic templates are used and with older standards where variadic functions are emulated by providing lightweight wrapper functions defined with theFMT_VARIADIC
macro. You can use this macro for defining your own portable variadic functions:void report_error(const char *format, const fmt::ArgList &args) { fmt::print("Error: {}"); fmt::print(format, args); } FMT_VARIADIC(void, report_error, const char *) report_error("file not found: {}", path);
Apart from a more natural syntax, this also improves performance as there is no need to construct temporary formatter objects and control arguments' lifetimes. Because the wrapper functions are very lightweight, this doesn't cause code bloat even in pre-C++11 mode.
Simplified common case of formatting an
std::string
. Now it requires a single function call:std::string s = format("The answer is {}.", 42);
Previously it required 2 function calls:
std::string s = str(Format("The answer is {}.") << 42);
Instead of unsafe
c_str
function,fmt::Writer
should be used directly to bypass creation ofstd::string
:fmt::Writer w; w.write("The answer is {}.", 42); w.c_str(); // returns a C string
This doesn't do dynamic memory allocation for small strings and is less error prone as the lifetime of the string is the same as for
std::string::c_str
which is well understood (hopefully).Improved consistency in naming functions that are a part of the public API. Now all public functions are lowercase following the standard library conventions. Previously it was a combination of lowercase and CapitalizedWords. Issue #50.
Old functions are marked as deprecated and will be removed in the next release.
Other Changes
Experimental support for printf format specifications (work in progress):
fmt::printf("The answer is %d.", 42); std::string s = fmt::sprintf("Look, a %s!", "string");
Support for hexadecimal floating point format specifiers
a
andA
:print("{:a}", -42.0); // Prints -0x1.5p+5 print("{:A}", -42.0); // Prints -0X1.5P+5
CMake option
FMT_SHARED
that specifies whether to build format as a shared library (off by default).
More efficient implementation of variadic formatting functions.
Writer::Format
now has a variadic overload:Writer out; out.Format("Look, I'm {}!", "variadic");
For efficiency and consistency with other overloads, variadic overload of the
Format
function now returnsWriter
instead ofstd::string
. Use thestr
function to convert it tostd::string
:std::string s = str(Format("Look, I'm {}!", "variadic"));
Replaced formatter actions with output sinks:
NoAction
->NullSink
,Write
->FileSink
,ColorWriter
->ANSITerminalSink
. This improves naming consistency and shouldn't affect client code unless these classes are used directly which should be rarely needed.Added
ThrowSystemError
function that formats a message and throwsSystemError
containing the formatted message and system-specific error description. For example, the following codeFILE *f = fopen(filename, "r"); if (!f) ThrowSystemError(errno, "Failed to open file '{}'") << filename;
will throw
SystemError
exception with description "Failed to open file '<filename>': No such file or directory" if file doesn't exist.Support for AppVeyor continuous integration platform.
Format
now throwsSystemError
in case of I/O errors.Improve test infrastructure. Print functions are now tested by redirecting the output to a pipe.
- Initial release