Visual Studio对C++20的支持

8

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

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


1
你是在问是否可以让一段代码实现它原本不实现的功能吗? - Nicol Bolas
1
@NicolBolas: 哎呀?我想要使用 std::format - Jonathan Wood
5
在项目属性中,选择 C/C++ -> 语言 ... ,然后选择“使用最新(预览)草案标准”。不过,我刚试了一下(在 VS 16.5.4 上),它并没有 <format> 头文件,所以我觉得你可能运气不好。 - Adrian Mole
1
@JonathanWood 不好意思,std::format还没有实现。实际上,没有任何标准库实现它。 - S.S. Anne
请注意,以下是微软C++语言合规性表 - https://learn.microsoft.com/en-us/cpp/overview/visual-cpp-language-conformance?view=vs-2019 - Richard Critten
显示剩余11条评论
3个回答

5
截至撰写时,没有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,否则会产生未定义的行为。 - S.S. Anne
1
Visual Studio 2019 v16.10 刚刚新增了 std::format - J. Willus

5
你可以使用 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编译即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接