涉及输出计时持续时间的 C++ 错误

标签 c++ struct chrono

这是我正在使用的类(class)(某些部分被剪掉了)

const int records = 7;

    class Timed {
    public:

        friend std::ostream& operator<<(std::ostream& os, Timed right) {
            for (int i = 0; i < records; i++) {
                os << right.eR[i].vName << " " << right.eR[i].duration << " " << right.eR[i].seconds << std::endl;
            }
            return os;
        }

    private:

        std::chrono::time_point<std::chrono::steady_clock> start, end;

        struct {
            std::string vName;
            std::string seconds;
            std::chrono::duration<float> duration;
        } eR[records];

    };
基本上,我正在尝试输出匿名结构的值。但是,我收到错误:
binary '<<': no operator found which takes a right-hand operand of type 'std::chrono::duration<float,std::ratio>1,1>>' (or there is no acceptable conversion)
我想知道如何在持续时间内打印此值?提前致谢

最佳答案

在 C++11/14/17 中,chrono::duration 没有流式运算符类型。你有两个选择:

  • 提取.count() :

  • |
     os << right.eR[i].duration.count() << "s ";
    
  • 使用这个open-source, header-only date/time library :

  • |
    #include "date/date.h"
    // ...
    using date::operator<<;
    os << right.eR[i].duration << " ";
    
    上面的 datelib 现在是 C++20 的一部分,但尚未发布。供应商正在为此努力。当您移植到它时,您只需删除 #include "date/date.h"using date::operator<<; .

    关于涉及输出计时持续时间的 C++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64181934/

    相关文章:

    c++ - 将一对添加到具有最少拷贝的 unordered_map 中

    c++ - C++中二进制模式的长度指示器

    c++ - core dumped,但没有找到错误位置,有GDB的错误信息

    c++ - 在 Qt 中如何运行进度条以指示其他进程正忙

    c - 打印结构的所有 "members"

    c++ - 检查 std::chrono 持续时间小于 0 的惯用方法

    C++ std::chrono::high_resolution_clock time_since_epoch 返回的数字太小。如何获得自 1970 年以来以微秒为单位的正确时间?

    c - 当数组在 c 中达到长度 0 时断言中止

    c++ - 在队列中插入 vector 元素

    c++ - 两个 time_point 实例之间的差异不是持续时间吗?