Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the <format> header

In a related question ("std::string formatting like sprintf") I learned about this awesome new C++20 header <format>.

However, there seems to be no supporting compiler. Is this correct or is there a way to use it anyway?
I'm using g++ 9.3 with the -std=c++2a flag and the library <format> is not recognised.

#include <format> // fatal error: format: No such file or directory
#include <iostream>

int main(){
    std::cout << std::format("Hello {}!", "World");
}

g++-9 test.cpp -o test -std=c++2a

like image 419
infinitezero Avatar asked Apr 26 '20 13:04

infinitezero


Video Answer


3 Answers

Use libfmt. The <format> header is essentially a standardized libfmt (with a few small features removed, if I remember correctly).

like image 59
HolyBlackCat Avatar answered Oct 18 '22 00:10

HolyBlackCat


There is a libfmt-dev package available on debian/ubuntu.
I currently use this header as a replacement for the format header:

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

namespace std
{
   template<typename... Args>
   inline auto format(Args&&... args) -> decltype(fmt::v7::format(std::forward<Args>(args)...))
   {
      return fmt::v7::format(std::forward<Args>(args)...);
   }
}

This is experimental: I don't know exactly what are the differences between std::format and fmt::format.
Life is full of surprises

like image 40
Kiruahxh Avatar answered Oct 17 '22 22:10

Kiruahxh


As of the time of writing, MSVC and Clang are the only 2 compilers supporting the header.

like image 1
fjch1997 Avatar answered Oct 17 '22 23:10

fjch1997