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表示没有匹配的“<<”运算符。
发布于 2021-01-30 00:10:57
您不希望将其转换为std::ostream,您希望将duration对象转换为可以插入到输出流中的类型(如整数、双值、.)。
os << t.events[i].duration.count();或者重载std::ostream& operator<<(std::ostream& os, chrono::steady_clock::duration duration)以定义如何显示它:
std::ostream& operator<<(std::ostream& os, chrono::steady_clock::duration duration)
{
os << "duration was " << duration.count() << ", ";
return os;
}发布于 2021-01-30 00:25:39
即将进入C++20 (仍由主要供应商实现)。如果您愿意,可以使用这个免费的,开放源码的,头只预览的C++20时间。预览程序适用于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。
https://stackoverflow.com/questions/65963238
复制相似问题