Visual Studio 中的 C++20 支持

Jon*_*ood 4 c++ stl visual-studio c++20 fmt

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

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

Pet*_*erT 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;
}
Run Code Online (Sandbox Code Playgroud)


JL2*_*210 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处处不合格要好。