API Reference

The {fmt} library API consists of the following parts:

  • fmt/core.h: the core API providing argument handling facilities and a lightweight subset of formatting functions
  • fmt/format.h: the full format API providing compile-time format string checks, wide string, output iterator and user-defined type support
  • fmt/ranges.h: additional formatting support for ranges and tuples
  • fmt/chrono.h: date and time formatting
  • fmt/compile.h: format string compilation
  • fmt/ostream.h: std::ostream support
  • fmt/printf.h: printf formatting

All functions and types provided by the library reside in namespace fmt and macros have prefix FMT_.

Core API

fmt/core.h defines the core API which provides argument handling facilities and a lightweight subset of formatting functions. In the header-only mode include fmt/format.h instead of fmt/core.h.

The following functions use format string syntax similar to that of Python’s str.format. They take format_str and args as arguments.

format_str is a format string that contains literal text and replacement fields surrounded by braces {}. The fields are replaced with formatted arguments in the resulting string. A function taking format_str doesn’t participate in an overload resolution if the latter is not a string.

args is an argument list representing objects to be formatted.

template <typename S, typename… Args, typename Char = char_t<S>>
std::basic_string<Char> fmt::format(const S &format_str, Args&&... args)

Formats arguments and returns the result as a string.

Example:

#include <fmt/core.h>
std::string message = fmt::format("The answer is {}", 42);

template <typename S, typename Char = char_t<S>>
std::basic_string<Char> fmt::vformat(const S &format_str, basic_format_args<buffer_context<type_identity_t<Char>>> args)
template <typename S, typename… Args, typename Char = char_t<S>>
void fmt::print(const S &format_str, Args&&... args)

Formats args according to specifications in format_str and writes the output to stdout. Strings are assumed to be Unicode-encoded unless the FMT_UNICODE macro is set to 0.

Example:

fmt::print("Elapsed time: {0:.2f} seconds", 1.23);

void fmt::buffered_file::vprint(string_view format_str, format_args args)
template <typename S, typename… Args, typename Char = char_t<S>>
void fmt::print(std::FILE *f, const S &format_str, Args&&... args)

Formats args according to specifications in format_str and writes the output to the file f. Strings are assumed to be Unicode-encoded unless the FMT_UNICODE macro is set to 0.

Example:

fmt::print(stderr, "Don't {}!", "panic");

void fmt::vprint(std::FILE *, string_view, format_args)

Named Arguments

template <typename Char, typename T>
detail::named_arg<Char, T> fmt::arg(const Char *name, const T &arg)

Returns a named argument to be used in a formatting function. It should only be used in a call to a formatting function.

Example:

fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23));

Named arguments are not supported in compile-time checks at the moment.

Argument Lists

template <typename Context = format_context, typename… Args>
format_arg_store<Context, Args...> fmt::make_format_args(const Args&... args)

Constructs an format_arg_store object that contains references to arguments and can be implicitly converted to format_args. Context can be omitted in which case it defaults to context. See arg() for lifetime considerations.

template <typename Context, typename… Args>
class

An array of references to arguments. It can be implicitly converted into basic_format_args for passing into type-erased formatting functions such as vformat().

template <typename Context>
class

A dynamic version of fmt::format_arg_store. It’s equipped with a storage to potentially temporary objects which lifetimes could be shorter than the format arguments object.

It can be implicitly converted into basic_format_args for passing into type-erased formatting functions such as vformat().

Public Functions

template <typename T>
void fmt::dynamic_format_arg_store::push_back(const T &arg)

Adds an argument into the dynamic store for later passing to a formatting function.

Note that custom types and string types (but not string views) are copied into the store dynamically allocating memory if necessary.

Example:

fmt::dynamic_format_arg_store<fmt::format_context> store;
store.push_back(42);
store.push_back("abc");
store.push_back(1.5f);
std::string result = fmt::vformat("{} and {} and {}", store);

template <typename T>
void fmt::dynamic_format_arg_store::push_back(std::reference_wrapper<T> arg)

Adds a reference to the argument into the dynamic store for later passing to a formatting function. Supports named arguments wrapped in std::reference_wrapper via std::ref()/std::cref().

Example:

fmt::dynamic_format_arg_store<fmt::format_context> store;
char str[] = "1234567890";
store.push_back(std::cref(str));
int a1_val{42};
auto a1 = fmt::arg("a1_", a1_val);
store.push_back(std::cref(a1));

// Changing str affects the output but only for string and custom types.
str[0] = 'X';

std::string result = fmt::vformat("{} and {a1_}");
assert(result == "X234567890 and 42");

template <typename T>
void fmt::dynamic_format_arg_store::push_back(const detail::named_arg<char_type, T> &arg)

Adds named argument into the dynamic store for later passing to a formatting function.

std::reference_wrapper is supported to avoid copying of the argument.

void fmt::dynamic_format_arg_store::clear()

Erase all elements from the store.

void fmt::dynamic_format_arg_store::reserve(size_t new_cap, size_t new_cap_named)

Reserves space to store at least new_cap arguments including new_cap_named named arguments.

template <typename Context>
class

A view of a collection of formatting arguments. To avoid lifetime issues it should only be used as a parameter type in type-erased functions such as vformat:

void vlog(string_view format_str, format_args args);  // OK
format_args args = make_format_args(42);  // Error: dangling reference

Public Functions

template <typename… Args>
fmt::basic_format_args::basic_format_args(const format_arg_store<Context, Args...> &store)

Constructs a basic_format_args object from format_arg_store.

fmt::basic_format_args::basic_format_args(const dynamic_format_arg_store<Context> &store)

Constructs a basic_format_args object from dynamic_format_arg_store.

fmt::basic_format_args::basic_format_args(const format_arg *args, int count)

Constructs a basic_format_args object from a dynamic set of arguments.

format_arg fmt::basic_format_args::get(int id) const

Returns the argument with the specified id.

struct

An alias to basic_format_args<context>.

Inherits from fmt::basic_format_args< format_context >

template <typename Context>
class

Compatibility

template <typename Char>
class

An implementation of std::basic_string_view for pre-C++17.

It provides a subset of the API. fmt::basic_string_view is used for format strings even if std::string_view is available to prevent issues when a library is compiled with a different -std option than the client code (which is not recommended).

Public Functions

constexpr fmt::basic_string_view::basic_string_view(const Char *s, size_t count)

Constructs a string reference object from a C string and a size.

fmt::basic_string_view::basic_string_view(const Char *s)

Constructs a string reference object from a C string computing the size with std::char_traits<Char>::length.

template <typename Traits, typename Alloc>
fmt::basic_string_view::basic_string_view(const std::basic_string<Char, Traits, Alloc> &s)

Constructs a string reference from a std::basic_string object.

constexpr const Char *fmt::basic_string_view::data() const

Returns a pointer to the string data.

constexpr size_t fmt::basic_string_view::size() const

Returns the string size.

using fmt::string_view = typedef basic_string_view<char>
using fmt::wstring_view = typedef basic_string_view<wchar_t>

Locale

All formatting is locale-independent by default. Use the 'n' format specifier to insert the appropriate number separator characters from the locale:

#include <fmt/core.h>
#include <locale>

std::locale::global(std::locale("en_US.UTF-8"));
auto s = fmt::format("{:L}", 1000000);  // s == "1,000,000"

Format API

fmt/format.h defines the full format API providing compile-time format string checks, wide string, output iterator and user-defined type support.

Compile-time Format String Checks

Compile-time checks are supported for built-in and string types as well as user-defined types with constexpr parse functions in their formatter specializations.

FMT_STRING(s)

Constructs a compile-time format string from a string literal s.

Example:

// A compile-time error because 'd' is an invalid specifier for strings.
std::string s = fmt::format(FMT_STRING("{:d}"), "foo");

Formatting User-defined Types

To make a user-defined type formattable, specialize the formatter<T> struct template and implement parse and format methods:

#include <fmt/format.h>

struct point { double x, y; };

template <>
struct fmt::formatter<point> {
  // Presentation format: 'f' - fixed, 'e' - exponential.
  char presentation = 'f';

  // Parses format specifications of the form ['f' | 'e'].
  constexpr auto parse(format_parse_context& ctx) {
  // auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) // c++11
    // [ctx.begin(), ctx.end()) is a character range that contains a part of
    // the format string starting from the format specifications to be parsed,
    // e.g. in
    //
    //   fmt::format("{:f} - point of interest", point{1, 2});
    //
    // the range will contain "f} - point of interest". The formatter should
    // parse specifiers until '}' or the end of the range. In this example
    // the formatter should parse the 'f' specifier and return an iterator
    // pointing to '}'.

    // Parse the presentation format and store it in the formatter:
    auto it = ctx.begin(), end = ctx.end();
    if (it != end && (*it == 'f' || *it == 'e')) presentation = *it++;

    // Check if reached the end of the range:
    if (it != end && *it != '}')
      throw format_error("invalid format");

    // Return an iterator past the end of the parsed range:
    return it;
  }

  // Formats the point p using the parsed format specification (presentation)
  // stored in this formatter.
  template <typename FormatContext>
  auto format(const point& p, FormatContext& ctx) {
  // auto format(const point &p, FormatContext &ctx) -> decltype(ctx.out()) // c++11
    // ctx.out() is an output iterator to write to.
    return format_to(
        ctx.out(),
        presentation == 'f' ? "({:.1f}, {:.1f})" : "({:.1e}, {:.1e})",
        p.x, p.y);
  }
};

Then you can pass objects of type point to any formatting function:

point p = {1, 2};
std::string s = fmt::format("{:f}", p);
// s == "(1.0, 2.0)"

You can also reuse existing formatters via inheritance or composition, for example:

enum class color {red, green, blue};

template <> struct fmt::formatter<color>: formatter<string_view> {
  // parse is inherited from formatter<string_view>.
  template <typename FormatContext>
  auto format(color c, FormatContext& ctx) {
    string_view name = "unknown";
    switch (c) {
    case color::red:   name = "red"; break;
    case color::green: name = "green"; break;
    case color::blue:  name = "blue"; break;
    }
    return formatter<string_view>::format(name, ctx);
  }
};

Since parse is inherited from formatter<string_view> it will recognize all string format specifications, for example

fmt::format("{:>10}", color::blue)

will return "      blue".

You can also write a formatter for a hierarchy of classes:

#include <type_traits>
#include <fmt/format.h>

struct A {
  virtual ~A() {}
  virtual std::string name() const { return "A"; }
};

struct B : A {
  virtual std::string name() const { return "B"; }
};

template <typename T>
struct fmt::formatter<T, std::enable_if_t<std::is_base_of<A, T>::value, char>> :
    fmt::formatter<std::string> {
  template <typename FormatCtx>
  auto format(const A& a, FormatCtx& ctx) {
    return fmt::formatter<std::string>::format(a.name(), ctx);
  }
};

int main() {
  B b;
  A& a = b;
  fmt::print("{}", a); // prints "B"
}
template <typename Char, typename ErrorHandler = detail::error_handler>
class

Parsing context consisting of a format string range being parsed and an argument counter for automatic indexing.

You can use one of the following type aliases for common character types:

Type Definition
format_parse_context basic_format_parse_context<char>
wformat_parse_context basic_format_parse_context<wchar_t>

Inherits from fmt::detail::error_handler

Public Functions

constexpr iterator fmt::basic_format_parse_context::begin() const

Returns an iterator to the beginning of the format string range being parsed.

constexpr iterator fmt::basic_format_parse_context::end() const

Returns an iterator past the end of the format string range being parsed.

void fmt::basic_format_parse_context::advance_to(iterator it)

Advances the begin iterator to it.

int fmt::basic_format_parse_context::next_arg_id()

Reports an error if using the manual argument indexing; otherwise returns the next argument index and switches to the automatic indexing.

void fmt::basic_format_parse_context::check_arg_id(int)

Reports an error if using the automatic argument indexing; otherwise switches to the manual indexing.

Output Iterator Support

template <typename OutputIt, typename S, typename… Args>
OutputIt fmt::format_to(OutputIt out, const S &format_str, Args&&... args)

Formats arguments, writes the result to the output iterator out and returns the iterator past the end of the output range.

Example:

std::vector<char> out;
fmt::format_to(std::back_inserter(out), "{}", 42);

template <typename OutputIt, typename S, typename… Args>
format_to_n_result<OutputIt> fmt::format_to_n(OutputIt out, size_t n, const S &format_str, const Args&... args)

Formats arguments, writes up to n characters of the result to the output iterator out and returns the total output size and the iterator past the end of the output range.

template <typename OutputIt>
struct

Public Members

OutputIt fmt::format_to_n_result::out

Iterator past the end of the output range.

size_t fmt::format_to_n_result::size

Total (not truncated) output size.

Literal-based API

The following user-defined literals are defined in fmt/format.h.

detail::udl_formatter<char> fmt::literals::operator""_format(const char *s, size_t n)

User-defined literal equivalent of fmt::format().

Example:

using namespace fmt::literals;
std::string message = "The answer is {}"_format(42);

detail::udl_arg<char> fmt::literals::operator""_a(const char *s, size_t)

User-defined literal equivalent of fmt::arg().

Example:

using namespace fmt::literals;
fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);

Utilities

template <typename T>
struct

Specifies if T is a character type.

Can be specialized by users.

Inherits from false_type

using fmt::char_t = typedef typename detail::char_t_impl<S>::type

String’s character type.

template <typename… Args>
size_t fmt::formatted_size(string_view format_str, const Args&... args)

Returns the number of characters in the output of format(format_str, args...).

template <typename T>
std::string fmt::to_string(const T &value)

Converts value to std::string using the default format for type T.

Example:

#include <fmt/format.h>

std::string answer = fmt::to_string(42);

template <typename T>
std::wstring fmt::to_wstring(const T &value)

Converts value to std::wstring using the default format for type T.

template <typename Char>
basic_string_view<Char> fmt::to_string_view(const Char *s)

Returns a string view of s. In order to add custom string type support to {fmt} provide an overload of to_string_view for it in the same namespace as the type for the argument-dependent lookup to work.

Example:

namespace my_ns {
inline string_view to_string_view(const my_string& s) {
  return {s.data(), s.length()};
}
}
std::string message = fmt::format(my_string("The answer is {}"), 42);

template <typename Range>
arg_join<detail::iterator_t<const Range>, detail::sentinel_t<const Range>, char> fmt::join(const Range &range, string_view sep)

Returns an object that formats range with elements separated by sep.

Example:

std::vector<int> v = {1, 2, 3};
fmt::print("{}", fmt::join(v, ", "));
// Output: "1, 2, 3"

fmt::join applies passed format specifiers to the range elements:

fmt::print("{:02}", fmt::join(v, ", "));
// Output: "01, 02, 03"

template <typename It, typename Sentinel>
arg_join<It, Sentinel, char> fmt::join(It begin, Sentinel end, string_view sep)

Returns an object that formats the iterator range [begin, end) with elements separated by sep.

template <typename T>
class

A contiguous memory buffer with an optional growing ability. It is an internal class and shouldn’t be used directly, only via basic_memory_buffer.

Subclassed by fmt::basic_memory_buffer< T, SIZE, Allocator >

Public Functions

size_t fmt::detail::buffer::size() const

Returns the size of this buffer.

size_t fmt::detail::buffer::capacity() const

Returns the capacity of this buffer.

T *fmt::detail::buffer::data()

Returns a pointer to the buffer data.

const T *fmt::detail::buffer::data() const

Returns a pointer to the buffer data.

void fmt::detail::buffer::resize(size_t new_size)

Resizes the buffer.

If T is a POD type new elements may not be initialized.

void fmt::detail::buffer::clear()

Clears this buffer.

void fmt::detail::buffer::reserve(size_t new_capacity)

Reserves space to store at least capacity elements.

template <typename U>
void fmt::detail::buffer::append(const U *begin, const U *end)

Appends data to the end of the buffer.

template <typename T, size_t SIZE = inline_buffer_size, typename Allocator = std::allocator<T>>
class

A dynamically growing memory buffer for trivially copyable/constructible types with the first SIZE elements stored in the object itself.

You can use one of the following type aliases for common character types:

Type Definition
memory_buffer basic_memory_buffer<char>
wmemory_buffer basic_memory_buffer<wchar_t>

Example:

fmt::memory_buffer out;
format_to(out, "The answer is {}.", 42);

This will append the following output to the out object:

The answer is 42.

The output can be converted to an std::string with to_string(out).

Inherits from fmt::detail::buffer< T >

Public Functions

fmt::basic_memory_buffer::basic_memory_buffer(basic_memory_buffer &&other)

Constructs a fmt::basic_memory_buffer object moving the content of the other object to it.

basic_memory_buffer &fmt::basic_memory_buffer::operator=(basic_memory_buffer &&other)

Moves the content of the other basic_memory_buffer object to this one.

Protected Functions

void fmt::basic_memory_buffer::grow(size_t capacity)

Increases the buffer capacity to hold at least capacity elements.

System Errors

fmt does not use errno to communicate errors to the user, but it may call system functions which set errno. Users should not make any assumptions about the value of errno being preserved by library functions.

class

An error returned by an operating system or a language runtime, for example a file opening error.

Inherits from runtime_error

Subclassed by fmt::windows_error

Public Functions

template <typename… Args>
fmt::system_error::system_error(int error_code, string_view message, const Args&... args)

Constructs a fmt::system_error object with a description formatted with fmt::format_system_error(). message and additional arguments passed into the constructor are formatted similarly to fmt::format().

Example:

// This throws a system_error with the description
//   cannot open file 'madeup': No such file or directory
// or similar (system message may vary).
const char *filename = "madeup";
std::FILE *file = std::fopen(filename, "r");
if (!file)
  throw fmt::system_error(errno, "cannot open file '{}'", filename);

void fmt::format_system_error(detail::buffer<char> &out, int error_code, string_view message)

Formats an error returned by an operating system or a language runtime, for example a file opening error, and writes it to out in the following form:

<message>: <system-message>

where <message> is the passed message and <system-message> is the system message corresponding to the error code. error_code is a system error code as given by errno. If error_code is not a valid error code such as -1, the system message may look like “Unknown error -1” and is platform-dependent.

class

A Windows error.

Inherits from fmt::system_error

Public Functions

template <typename… Args>
fmt::windows_error::windows_error(int error_code, string_view message, const Args&... args)

Constructs a fmt::windows_error object with the description of the form

<message>: <system-message>

where <message> is the formatted message and <system-message> is the system message corresponding to the error code. error_code is a Windows error code as given by GetLastError. If error_code is not a valid error code such as -1, the system message will look like “error -1”.

Example:

// This throws a windows_error with the description
//   cannot open file 'madeup': The system cannot find the file specified.
// or similar (system message may vary).
const char *filename = "madeup";
LPOFSTRUCT of = LPOFSTRUCT();
HFILE file = OpenFile(filename, &of, OF_READ);
if (file == HFILE_ERROR) {
  throw fmt::windows_error(GetLastError(),
                           "cannot open file '{}'", filename);
}

Custom Allocators

The {fmt} library supports custom dynamic memory allocators. A custom allocator class can be specified as a template argument to fmt::basic_memory_buffer:

using custom_memory_buffer =
  fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;

It is also possible to write a formatting function that uses a custom allocator:

using custom_string =
  std::basic_string<char, std::char_traits<char>, custom_allocator>;

custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
                      fmt::format_args args) {
  custom_memory_buffer buf(alloc);
  fmt::vformat_to(buf, format_str, args);
  return custom_string(buf.data(), buf.size(), alloc);
}

template <typename ...Args>
inline custom_string format(custom_allocator alloc,
                            fmt::string_view format_str,
                            const Args& ... args) {
  return vformat(alloc, format_str, fmt::make_format_args(args...));
}

The allocator will be used for the output container only. If you are using named arguments, the container that stores pointers to them will be allocated using the default allocator. Also floating-point formatting falls back on sprintf which may do allocations.

Ranges and Tuple Formatting

The library also supports convenient formatting of ranges and tuples:

#include <fmt/ranges.h>

std::tuple<char, int, float> t{'a', 1, 2.0f};
// Prints "('a', 1, 2.0)"
fmt::print("{}", t);

NOTE: currently, the overload of fmt::join for iterables exists in the main format.h header, but expect this to change in the future.

Using fmt::join, you can separate tuple elements with a custom separator:

#include <fmt/ranges.h>

std::tuple<int, char> t = {1, 'a'};
// Prints "1, a"
fmt::print("{}", fmt::join(t, ", "));

Date and Time Formatting

The library supports strftime-like date and time formatting:

#include <fmt/chrono.h>

std::time_t t = std::time(nullptr);
// Prints "The date is 2016-04-29." (with the current date)
fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t));

The format string syntax is described in the documentation of strftime.

Format string compilation

fmt/compile.h provides format string compilation support. Format strings are parsed at compile time and converted into efficient formatting code. This supports arguments of built-in and string types as well as user-defined types with constexpr parse functions in their formatter specializations. Format string compilation can generate more binary code compared to the default API and is only recommended in places where formatting is a performance bottleneck.

FMT_COMPILE(s)

Converts a string literal s into a format string that will be parsed at compile time and converted into efficient formatting code. Requires C++17 constexpr if compiler support.

Example:

// Converts 42 into std::string using the most efficient method and no
// runtime format string processing.
std::string s = fmt::format(FMT_COMPILE("{}"), 42);

std::ostream Support

fmt/ostream.h provides std::ostream support including formatting of user-defined types that have overloaded operator<<:

#include <fmt/ostream.h>

class date {
  int year_, month_, day_;
public:
  date(int year, int month, int day): year_(year), month_(month), day_(day) {}

  friend std::ostream& operator<<(std::ostream& os, const date& d) {
    return os << d.year_ << '-' << d.month_ << '-' << d.day_;
  }
};

std::string s = fmt::format("The date is {}", date(2012, 12, 9));
// s == "The date is 2012-12-9"
template <typename S, typename… Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
void fmt::print(std::basic_ostream<Char> &os, const S &format_str, Args&&... args)

Prints formatted data to the stream os.

Example:

fmt::print(cerr, "Don't {}!", "panic");

printf Formatting

The header fmt/printf.h provides printf-like formatting functionality. The following functions use printf format string syntax with the POSIX extension for positional arguments. Unlike their standard counterparts, the fmt functions are type-safe and throw an exception if an argument type doesn’t match its format specification.

template <typename S, typename… Args>
int fmt::printf(const S &format_str, const Args&... args)

Prints formatted data to stdout.

Example:

fmt::printf("Elapsed time: %.2f seconds", 1.23);

template <typename S, typename… Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
int fmt::fprintf(std::FILE *f, const S &format, const Args&... args)

Prints formatted data to the file f.

Example:

fmt::fprintf(stderr, "Don't %s!", "panic");

template <typename S, typename… Args, typename Char = char_t<S>>
int fmt::fprintf(std::basic_ostream<Char> &os, const S &format_str, const Args&... args)

Prints formatted data to the stream os.

Example:

fmt::fprintf(cerr, "Don't %s!", "panic");

template <typename S, typename… Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
std::basic_string<Char> fmt::sprintf(const S &format, const Args&... args)

Formats arguments and returns the result as a string.

Example:

std::string message = fmt::sprintf("The answer is %d", 42);

Compatibility with C++20 std::format

{fmt} implements nearly all of the C++20 formatting library with the following differences:

  • Names are defined in the fmt namespace instead of std to avoid collisions with standard library implementations.
  • The 'L' format specifier cannot be combined with presentation specifiers yet.
  • Width calculation doesn’t use grapheme clusterization. The latter has been implemented in a separate branch but hasn’t been integrated yet.
  • Chrono formatting doesn’t support C++20 date types since they are not provided by standard library implementations.