Namespaces
Variants
Actions

std::common_type<std::chrono::duration>

From cppreference.com
< cpp‎ | chrono‎ | duration
 
C++
 
Date and time library
Time point
(C++11)
(C++20)
Duration
(C++11)
Clocks
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
Time of day
(C++20)(C++20)
(C++20)(C++20)
(C++20)
Calendar
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)(C++20)
chrono I/O
(C++20)

 
std::chrono::duration
Defined in header <chrono>
template< class Rep1, class Period1, class Rep2, class Period2 >

struct common_type<std::chrono::duration<Rep1, Period1>,

                   std::chrono::duration<Rep2, Period2>>;
(since C++11)

Exposes the type named type, which is the common type of two std::chrono::durations, whose period is the greatest common divisor of Period1 and Period2.

Contents

[edit] Member types

Member type Definition
type std::chrono::duration<typename std::common_type<Rep1, Rep2>::type, /* see note */>

[edit] Note

The period of the resulting duration can be computed by forming a ratio of the greatest common divisor of Period1::num and Period2::num and the least common multiple of Period1::den and Period2::den.

[edit] Example

#include <chrono>
#include <iostream>
#include <type_traits>
 
/ std::chrono already finds the greatest common divisor,
/ likely using std::common_type<>. We make the type
/ deduction externally. 
 
template<typename T,typename S>
constexpr auto durationDiff(const T& t, const S& s)
    -> typename std::common_type<T,S>::type
{
    typedef typename std::common_type<T,S>::type Common;
    return Common(t) - Common(s);
}
 
int main() 
{
    using namespace std::literals;
 
    constexpr auto ms = 30ms;
    constexpr auto us = 1100us;
    constexpr auto diff = durationDiff(ms, us);
 
    std::cout << ms << " - " << us << " = " << diff << '\n';
}

Output:

30ms - 1100us = 28900us

[edit] See also

specializes the std::common_type trait
(class template specialization) [edit]
determines the common type of a group of types
(class template) [edit]

Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant