首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将chrono::steady_clock::duration转换为ostream?

如何将chrono::steady_clock::duration转换为ostream?
EN

Stack Overflow用户
提问于 2021-01-29 23:52:24
回答 2查看 154关注 0票数 1
代码语言:javascript
复制
    ostream& operator<<(ostream& os, const TimedEvents& t)
    {
        os << "Execution Times:\n--------------------------\n";
        
        for (int i = 0; i < t.nEvents; i++)
        {
            os << os.width(21) << t.events[i].name << ' ';
            os.width(13);
            os.setf(ios::right);
            os << t.events[i].duration << os.unsetf(ios::left) << ' ' << t.events[i].units << endl;
        }
        cout << "--------------------------" << endl;

        return os;
    }

在上面的代码中,os << t.events[i].duration将无法工作,因为我无法将工期转换为ostream。工期是一个chrono::steady_clock::duration,Visual表示没有匹配的“<<”运算符。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-01-30 00:10:57

您不希望将其转换为std::ostream,您希望将duration对象转换为可以插入到输出流中的类型(如整数、双值、.)。

代码语言:javascript
复制
os << t.events[i].duration.count();

或者重载std::ostream& operator<<(std::ostream& os, chrono::steady_clock::duration duration)以定义如何显示它:

代码语言:javascript
复制
std::ostream& operator<<(std::ostream& os, chrono::steady_clock::duration duration)
{
    os << "duration was " << duration.count() << ", ";
    return os;
}
票数 2
EN

Stack Overflow用户

发布于 2021-01-30 00:25:39

即将进入C++20 (仍由主要供应商实现)。如果您愿意,可以使用这个免费的,开放源码的,头只预览的C++20时间。预览程序适用于C++11/14/17:

代码语言:javascript
复制
#include "date/date.h"  // add this

ostream& operator<<(ostream& os, const TimedEvents& t)
{
    using date::operator<<;  // add this
    os << "Execution Times:\n--------------------------\n";
    
    for (int i = 0; i < t.nEvents; i++)
    {
        os << os.width(21) << t.events[i].name << ' ';
        os.width(13);
        os.setf(ios::right);
        os << t.events[i].duration << os.unsetf(ios::left) << ' ' << t.events[i].units << endl;
    }
    cout << "--------------------------" << endl;

    return os;
}

这将同时输出持续时间的值和单位。

如果您想自己去做,您可以使用.count()成员函数来获得值,如果您知道这些单位,就打印一些东西来表示这个值。如果你不知道单位,你可以使用duration的嵌套类型period::numperiod::den来得到持续时间所代表的秒的分数的分子和分母,例如毫秒,分别是1和1000。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65963238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档