【问题标题】:C++20 support in Visual StudioVisual Studio 中的 C++20 支持
【发布时间】:2020-08-17 01:17:48
【问题描述】:

我想使用 std::format,但 Visual Studio 说 std 命名空间没有成员 format

这似乎是 C++20 的新功能。有没有办法让它可用?

【问题讨论】:

  • 您是在问是否可以使一段代码实现它没有实现的东西?
  • 你用的是哪个版本?
  • @NicolBolas:嗯?我想使用std::format
  • @JonathanWood 在项目属性 -> C/C++ -> 语言 ... 选择“使用最新(预览)草案标准” 但是,我刚刚尝试过(VS 16.5.4)但它没有有 <format> 标题 - 所以我认为你不走运。
  • @JonathanWood 不,抱歉。 std::format 尚未实现。实际上,没有标准库实现它。

标签: c++ visual-studio stl c++20 fmt


【解决方案1】:

截至撰写本文时,没有 C++ 标准库实现 std::format

网络上有各种可用的实现,例如https://github.com/fmtlib/fmt(可能是提案的原始来源,在fmt::)和https://github.com/mknejp/std-format(将所有内容都放在std::experimental::)。

我不建议将它们拉入std。如果我不得不处理这样的事情,我会选择的解决方案是:

  • 添加#define <some-unique-name>_format <wherever>::format,然后使用<some-unique-name>_format

  • 然后,一旦您获得std::format 支持,搜索并替换<some-unique-name>_formatstd::format 并折腾#define

它使用宏,但从长远来看,它比到处都有不合格的format 要好。

【讨论】:

  • @TemplateRex 你建议做什么?命名空间别名不能拉入std;否则,这将是未定义的行为
  • Visual Studio 2019 v16.10 刚刚添加了std::format!
【解决方案2】:

您可以使用 fmt 作为一种 polyfill。它不完全相同,但具有重要的功能重叠。因此,如果您对如何使用它很谨慎,您可以在获得支持后将其换成<format>

#include <string>
#include <version>
#ifndef __cpp_lib_format
#include <fmt/core.h>
using fmt::format;
#else
#include <format>
using std::format;
#endif

int main()
{
    std::string a = format("test {}",43);
    return 0;
}

【讨论】:

    【解决方案3】:

    从 Visual Studio 2019 版本 16.10(2021 年 5 月 25 日发布)开始,添加了对 std::format 的支持。只需使用/std:c++latest 编译即可。

    【讨论】:

      猜你喜欢
      • 2020-03-19
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 2017-02-09
      • 2011-02-16
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      相关资源
      最近更新 更多