std::chrono::treat_as_floating_point
来自 cppreference.com
定义在头文件 <chrono> 中 |
||
template< class Rep > struct treat_as_floating_point : std::is_floating_point<Rep> {}; |
(自 C++11 起) | |
std::chrono::treat_as_floating_point
特性有助于确定是否可以将持续时间转换为具有不同刻度周期的另一个持续时间。
两个持续时间之间的隐式转换通常取决于持续时间的刻度周期。但是,如果 std::chrono::treat_as_floating_point<Rep>::value 为 true,则无论刻度周期如何,都可以进行隐式转换。
内容 |
[编辑] 辅助变量模板
template< class Rep > constexpr bool treat_as_floating_point_v = treat_as_floating_point<Rep>::value; |
(自 C++17 起) | |
[编辑] 特化
std::chrono::treat_as_floating_point
可以针对程序定义的类型进行特化。
[编辑] 示例
运行此代码
#include <chrono> #include <iostream> #include <thread> void timed_piece_of_code() { std::chrono::milliseconds simulated_work(2); std::this_thread::sleep_for(simulated_work); } int main() { auto start = std::chrono::high_resolution_clock::now(); std::cout << "Running some timed piece of code...\n"; timed_piece_of_code(); auto stop = std::chrono::high_resolution_clock::now(); // A floating point milliseconds type using FpMilliseconds = std::chrono::duration<float, std::chrono::milliseconds::period>; static_assert(std::chrono::treat_as_floating_point<FpMilliseconds::rep>::value, "Rep required to be floating point"); // Note that implicit conversion is not allowed here auto i_ms = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); // Note that implicit conversion is allowed here auto f_ms = FpMilliseconds(stop - start); std::cout << "Timing stats:\n"; std::cout << " Time in milliseconds, using default rep: " << i_ms.count() << '\n'; std::cout << " Time in milliseconds, using floating point rep: " << f_ms.count() << '\n'; }
可能的输出
Running some timed piece of code... Timing stats: Time in milliseconds, using default rep: 2 Time in milliseconds, using floating point rep: 2.57307