【问题标题】:How to use the <format> header如何使用 <format> 标头
【发布时间】:2020-08-09 23:33:47
【问题描述】:

在一个相关问题 ("std::string formatting like sprintf") 中,我了解到这个很棒的新 C++20 标头 <format>

但是,there seems to be no supporting compiler。这是正确的还是有办法使用它?
我正在使用带有 -std=c++2a 标志的 g++ 9.3,并且无法识别库 &lt;format&gt;

#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

【问题讨论】:

    标签: c++ formatting g++ header-files c++20


    【解决方案1】:

    使用libfmt&lt;format&gt; 标头本质上是一个标准化的 libfmt(如果我没记错的话,删除了一些小功能)。

    【讨论】:

    • " 标头深受其启发。" 不,那个项目是 touted as 一个"完整的实现"图书馆。
    • @NicolBolas 我可能错了,但 libfmt 不是早于&lt;format&gt; 提案吗?
    • 它可能早于提案,但它似乎跟踪了提案的发展。因为,您知道,提案和库是由同一个人编写的;)
    • @NicolBolas 哦。我会改变措辞。
    • 谢谢,我通过以下步骤使它工作: 1. 像往常一样克隆 repo,生成构建子目录,cmake ..(带有您想要的选项)和make。 2. 将make install 添加到您的系统中,或者将包含路径、库路径和库链接添加到您的C++ 项目配置中。 3. 将#include &lt;format&gt;" 替换为#include &lt;fmt/format.h&gt;(或"fmt/format.h",如果您不认为它是系统标头)。 4. 将所有std::(format function) 替换为fmt::(format function)。如果您想要在将 添加到 std 时不会更改的不可知代码,您将需要一个代理...
    【解决方案2】:

    在 debian/ubuntu 上有一个 libfmt-dev 软件包。
    我目前使用此标头替代format 标头:

    #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)...); \
       }
    }
    

    这是实验性的:我不知道 std::formatfmt::format 之间的确切区别。
    生活充满惊喜

    【讨论】:

    • 感谢您的回答,但其他答案中已经提到了这个库
    • 有了这个头文件,fmtlib 是 std::format 的一个替代品:你可以在 std::format 和 fmt::format 之间切换而无需修改你的代码。
    猜你喜欢
    • 2011-07-02
    • 2021-11-12
    • 2015-04-29
    • 2020-03-20
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    相关资源
    最近更新 更多