std::chrono::treat_as_floating_point

From cppreference.com
< cpp‎ | chrono
 
 
 
 
 
Defined in header <chrono>
template <class Rep>
struct treat_as_floating_point : std::is_floating_point<Rep> {};
(since C++11)

The std::chrono::treat_as_floating_point trait helps determine if a duration can be converted to another duration with a different tick period.

Implicit conversions between two durations normally depends on the tick period of the durations. However, implicit conversions can happen regardless of tick period if std::chrono::treat_as_floating_point<Rep>::value == true.

[edit] Example

#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();
 
    // A floating point milliseconds type
    typedef std::chrono::duration<float, std::chrono::milliseconds::period> fp_milliseconds;
 
    static_assert(
        std::chrono::treat_as_floating_point<fp_milliseconds::rep>::value, 
        "Rep required to be floating point"
    );
 
    // Note that implicit conversion is not allowed here
    std::cout << "Time in milliseconds, using default rep: "
              << std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count()
              << '\n';
 
    // Note that implicit conversion is allowed here
    std::cout << "Time in milliseconds, using floating point rep: "
              << fp_milliseconds(stop - start).count() 
              << '\n';
 
}

Possible output:

Running some timed piece of code...
Timing stats:
  Time in milliseconds, using default rep: 2
  Time in milliseconds, using floating point rep: 2.57307