What serious alternatives exist for the IOStream library? (besides cstdio)

The {fmt} library: I just stumbled across it from a YouTube talk and it seems to be quite nice.

A formatting facility based on {fmt} has been proposed for standardization in C++20: P0645. Both P0645 and {fmt} use a Python-like format string syntax which is similar to printf‘s but uses {} as delimiters instead of %.

For example

#include <fmt/core.h>

int main() {
  fmt::print("The answer is {}.", 42);
}

prints “The answer is 42.” to stdout.

The std::format function proposed for C++20:

#include <format>

int main() {
  std::string s = std::format("The answer is {}.", 42);
}

Notable features of {fmt}:

  1. Type and memory safety with errors in format strings optionally reported at compile time.

  2. Extensibility: users can write formatters for their types, including custom format specification parsers (as in Python).

  3. Compact binary code. The print example above compiles to just:

    main: # @main
      sub rsp, 24
      mov qword ptr [rsp], 42
      mov rcx, rsp
      mov edi, offset .L.str
      mov esi, 17
      mov edx, 2
      call fmt::v5::vprint(fmt::v5::basic_string_view<char>, fmt::v5::format_args)
      xor eax, eax
      add rsp, 24
      ret
    .L.str:
      .asciz "The answer is {}."
    

    which is comparable to printf and much better than iostreams.

  4. Performance: {fmt} is considerably faster than common implementations of printf and iostreams. Here are results from a tinyformat benchmark on macOS with clang:

    ================= ============= ===========
    Library           Method        Run Time, s
    ================= ============= ===========
    libc              printf          1.01
    libc++            std::ostream    3.04
    {fmt} 1632f72     fmt::print      0.86
    tinyformat 2.0.1  tfm::printf     3.23
    Boost Format 1.67 boost::format   7.98
    Folly Format      folly::format   2.23
    ================= ============= ===========
    

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)