7

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

看来这对于 C++20 来说是新的。有没有办法让它可用?

4

3 回答 3

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;
}
于 2020-05-02T15:02:35.303 回答
5

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

网络上有各种可用的实现,比如https://github.com/fmtlib/fmt(大概是提案的原始来源,in fmt::)和https://github.com/mknejp/std-format(把所有中std::experimental::)。

我不建议将这些拉入std. 如果我不得不处理这样的事情,我会寻求的解决方案是:

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

  • 然后,一旦你得到std::format支持,<some-unique-name>_format用.std::format#define

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

于 2020-05-02T15:03:33.950 回答
3

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

于 2021-10-01T23:46:02.373 回答