Visual Studio 中的 C++20 支持

C++20 support in Visual Studio

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

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

您可以使用 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;
}

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

Web 上有各种可用的实现,例如 https://github.com/fmtlib/fmt (presumably the original source of the proposal, in fmt::) and 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

自 Visual Studio 2019 版本 16.10(2021 年 5 月 25 日发布)发布以来,添加了对 std::format 的支持。只需使用 /std:c++latest.

编译