【问题标题】:How do I convert chrono::steady_clock::duration to ostream?如何将 chrono::steady_clock::duration 转换为 ostream?
【发布时间】:2021-01-29 23:52:24
【问题描述】:
    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 &lt;&lt; t.events[i].duration 不起作用,因为我无法将持续时间转换为 ostream。持续时间是 chrono::steady_clock::duration,Visual Studio 说没有匹配的“

【问题讨论】:

标签: c++


【解决方案1】:

您不想将其转换为std::ostream,您想将持续时间对象转换为可插入输出流的类型(如整数、双精度、...)。

os << t.events[i].duration.count();

或重载std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, chrono::steady_clock::duration duration) 以定义您希望它的显示方式:

std::ostream& operator<<(std::ostream& os, chrono::steady_clock::duration duration)
{
    os << "duration was " << duration.count() << ", ";
    return os;
}

【讨论】:

    【解决方案2】:

    A streaming operator for std::chrono::duration is coming in C++20(主要供应商仍在实施)。如果您愿意,可以使用此free, open-source, header-only preview of C++20 chrono。预览版适用于 C++11/14/17:

    #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::num 和period::den 来获取持续时间所代表的秒数分数的分子和分母。例如毫秒,分别是 1 和 1000。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多