C++ 命名空间 "std" 没有成员 "format" 尽管 #include <format>

C++ namespace "std" has no member "format" despite #include <format>

我是 C++ 新手。我正在尝试将当前日期和时间存储为字符串变量。

,我找到了答案,并安装了 date.h 库。

但是,当我尝试使用提供的代码时,遇到了错误:

namespace "std" has no member "format"

尽管脚本顶部有 #include <format>

我该如何解决这个问题?

我在 Windows 10 上使用 Visual Studio 2022,如果有帮助的话。

这是我的代码:

#include <iostream>
#include <chrono>
#include <date.h>
#include <type_traits>
#include <format>


int main()
{
    std::cout << "The current time is ";
    auto start_time = std::format("{:%F %T}", std::chrono::system_clock::now());
    static_assert(std::is_same_v<decltype(start_time), std::string>{});
    std::cout << start_time << "\n";
}

std::format 是在 C++20 标准中添加到 C++ 中的。除非你用 C++20 编译,否则你不会有 std::format.

截至 2021 年 12 月,std::format 和其他一些 C++20 设施仅在 Visual Studio 2019/std:c++latest 模式下可用2022.

Here is a quote:

As part of implementing C++20, there were some late discoveries which required changes to the ISO C++20 standard via the standard committee’s Defect Report (DR) process. This included Existing implementations (pre-DR) for these features are available under the /std:c++latest switch. We’re also tracking the DRs and are implementing those issue resolutions under /std:c++latest. Our plan is to make these capabilities available under the /std:c++20 switch after implementation of the full set of Standard Library DRs has completed.

Microsoft 完成所有 DR 实施后,std::format 将在 /std:c++20 开关下可用。

使用#include <algorithm>

对于那些 运行 遇到这个问题的人,使用 GCC 或 clang。编译器仅部分支持 c++20 中的所有新模块 https://en.cppreference.com/w/cpp/compiler_support/20