c++ - 与 'operator<<' const std::chrono::duration<double, std::milli> 不匹配

标签 c++ c++-chrono

我正在尝试运行此cppreference example用于分析我的代码:

#include <chrono>
#include <iostream>
#include <ratio>
#include <thread>
 
void f()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
int main()
{
    const auto t1 = std::chrono::high_resolution_clock::now();
    f();
    const auto t2 = std::chrono::high_resolution_clock::now();
 
    // floating-point duration: no duration_cast needed
    const std::chrono::duration<double, std::milli> fp_ms = t2 - t1;
 
    // integral duration: requires duration_cast
    const auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
 
    // converting integral duration to integral duration of
    // shorter divisible time unit: no duration_cast needed
    const std::chrono::duration<long, std::micro> int_usec = int_ms;
 
    std::cout << "f() took " << fp_ms << ", or "
              << int_ms << " (whole milliseconds), or "
              << int_usec << " (whole microseconds)\n";
}

但是,我不断收到此错误:

    >’ is not derived from ‘const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>’
         std::cout << "f() took " << fp_ms << ", or "

我正在传递 -std=c++11-std=c++17 但没有成功。

我使用的是g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0

编辑:

显然,我需要传递 -std=c++20 但我的 g++ 版本不支持它。现在的问题是如何为我的 g++ 版本获取此功能或类似功能。

最佳答案

不幸的是,std::chrono不提供 operator<< 的实现对于 std::chrono::duration类型 until C++20 .

但是,通过使用 .count(),您可以使用 STL 的 C++17 或 C++14 版本(可能也可以使用 C++11)获得大致相同的结果。 duration 的成员函数类(class)。代码的等效输出行如下所示:

std::cout << "f() took " << fp_ms.count() << ", or "
    << int_ms.count() << " (whole milliseconds), or "
    << int_usec.count() << " (whole microseconds)\n";

或者,您可以实现相关的 operator<<如果检测到的编译标准低于 C++20,则重载为函数模板。以下内容将允许您的输出代码按原样使用:

#if __cplusplus < 202002L
template <class rep, class period>
std::ostream& operator<<(std::ostream& os, std::chrono::duration<rep, period> value) {
    os << value.count();
    // Edited to check for (some) unit suffixes; you can others as you want ...
    if constexpr (std::is_same<std::micro, period>::value) os << "us";
    else if constexpr (std::is_same<std::milli, period>::value) os << "ms";
    else os << "s"; // ^^ Pre-C++17, you'll need to omit the "constexpr" keywords!
    return os;
}
#endif

关于c++ - 与 'operator<<' const std::chrono::duration<double, std::milli> 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77326294/

相关文章:

c++ - 将 std::duration 转换为人类可读的时间

c++ - 使用 Howard Hinnant 的库解析带有时区名称的日期/时间时出现问题

c++ - 模板函数错误

c++ - Visual Studio Code 在调试时使用输入文本文件

c++ - 制作汇编器的设计模式

c++ - 基于<chrono>改进一个定时器类

c++ - std::chrono::duration_cast count() 返回零

c++ - 将来调用 system_clock::now() 可以给出过去的时间吗?

c++ - 如何解析语法简单的输入命令?

C++错误: no match for 'operator<<' (operand types are