std::chrono:: treat_as_floating_point
From cppreference.net
C++
Date and time library
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::chrono::duration
| Member functions | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Non-member functions | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Helper classes | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
定义于头文件
<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 << "正在运行计时代码段...\n"; timed_piece_of_code(); auto stop = std::chrono::high_resolution_clock::now(); // 浮点型毫秒时长类型 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"); // 注意此处不允许隐式转换 auto i_ms = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); // 注意此处允许隐式转换 auto f_ms = FpMilliseconds(stop - start); std::cout << "计时统计:\n"; std::cout << " 使用默认rep的毫秒时间:" << i_ms.count() << '\n'; std::cout << " 使用浮点rep的毫秒时间:" << f_ms.count() << '\n'; }
可能的输出:
正在运行计时代码段... 计时统计: 使用默认rep的毫秒时间:2 使用浮点rep的毫秒时间:2.57307