std::chrono::treat_as_floating_point

来自cppreference.com
< cpp‎ | chrono
 
 
工具库
类型支持(基本类型、 RTTI 、类型特性)
动态内存管理
错误处理
程序工具
变参数函数
日期和时间
函数对象
(C++11)
关系运算符
optionalanyvariant (C++17)
pair 与 tuple
(C++11)
(C++17)
swap 、 forward 与 move
(C++14)
(C++11)
(C++11)
初等字符串转换
(C++17)
(C++17)
类型运算
(C++11)
(C++17)
 
 
 
定义于头文件 <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 >
inline constexpr bool treat_as_floating_point_v = treat_as_floating_point<Rep>::value;
(C++17 起)

[编辑] 示例

#include <iostream>
#include <chrono>
#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();
 
    // 浮点毫秒类型
    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 << "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

[编辑] 参阅