我正在尝试运行此cppreference example用于分析我的代码:
#include <chrono>
#include <iostream>
#include <ratio>
#include <thread>
void f()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
const auto t1 = std::chrono::high_resolution_clock::now();
f();
const auto t2 = std::chrono::high_resolution_clock::now();
// floating-point duration: no duration_cast needed
const std::chrono::duration<double, std::milli> fp_ms = t2 - t1;
// integral duration: requires duration_cast
const auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
// converting integral duration to integral duration of
// shorter divisible time unit: no duration_cast needed
const std::chrono::duration<long, std::micro> int_usec = int_ms;
std::cout << "f() took " << fp_ms << ", or "
<< int_ms << " (whole milliseconds), or "
<< int_usec << " (whole microseconds)\n";
}
但是,我不断收到此错误:
>’ is not derived from ‘const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>’
std::cout << "f() took " << fp_ms << ", or "
我正在传递 -std=c++11
和 -std=c++17
但没有成功。
我使用的是g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
。
编辑:
显然,我需要传递 -std=c++20 但我的 g++ 版本不支持它。现在的问题是如何为我的 g++ 版本获取此功能或类似功能。
最佳答案
不幸的是,std::chrono
不提供 operator<<
的实现对于 std::chrono::duration
类型 until C++20 .
但是,通过使用 .count()
,您可以使用 STL 的 C++17 或 C++14 版本(可能也可以使用 C++11)获得大致相同的结果。 duration
的成员函数类(class)。代码的等效输出行如下所示:
std::cout << "f() took " << fp_ms.count() << ", or "
<< int_ms.count() << " (whole milliseconds), or "
<< int_usec.count() << " (whole microseconds)\n";
或者,您可以实现相关的 operator<<
如果检测到的编译标准低于 C++20,则重载为函数模板。以下内容将允许您的输出代码按原样使用:
#if __cplusplus < 202002L
template <class rep, class period>
std::ostream& operator<<(std::ostream& os, std::chrono::duration<rep, period> value) {
os << value.count();
// Edited to check for (some) unit suffixes; you can others as you want ...
if constexpr (std::is_same<std::micro, period>::value) os << "us";
else if constexpr (std::is_same<std::milli, period>::value) os << "ms";
else os << "s"; // ^^ Pre-C++17, you'll need to omit the "constexpr" keywords!
return os;
}
#endif
关于c++ - 与 'operator<<' const std::chrono::duration<double, std::milli> 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77326294/