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

给你一囗甜甜゛ 提交于 2019-11-29 20:51:15

You might be interested in Fast Format library. You can see the comparison on their website with various other libraries as well.

Boost.Spirit.Qi for input, Boost.Spirit.Karma for output. Can read from/write to anything that can be represented as an iterator range.

smoothware

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
    ================= ============= ===========
    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!