【问题标题】:How do I print a `chrono` duration with units with Howard Hinnant's date.h?如何打印带有 Howard Hinnant 的 date.h 单位的“chrono”持续时间?
【发布时间】:2021-02-15 01:00:41
【问题描述】:

我有以下玩具代码:

#include "date/date.h"
#include <iostream>

using namespace std;
using namespace chrono;

int main() {
    cout << microseconds(100);
};

但是,它不起作用,因为:

C2679: binary '<<': no operator found which takes a right-hand operand of type 'std::chrono::milliseconds' (or there is no acceptable conversion)

但是docsdate.h 列出了规范:

template <class CharT, class Traits, class Rep, class Period>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
           const std::chrono::duration<Rep, Period>& d);

它将使用get_units 输出适当的单位。

那么,我该如何正确使用这个重载的&lt;&lt; 运算符呢?

【问题讨论】:

  • 您的代码看起来与duration 中的示例不同。

标签: c++ chrono


【解决方案1】:

operator&lt;&lt; 位于 date 命名空间内。由于这两种操作数类型都不是来自此命名空间,因此依赖于参数的查找将找不到它。

要使用它,您需要using namespace dateusing date::operator&lt;&lt;

您的代码中的另一个问题是 microseconds 只能从整数类型构造,而不是浮点数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    相关资源
    最近更新 更多