std::common_type(std::chrono::duration)

From cppreference.com
< cpp‎ | chrono‎ | duration
 
 
Utilities library
Type support (basic types, RTTI, type traits)
Dynamic memory management
Error handling
Program utilities
Variadic functions
Date and time
Function objects
(C++11)
Relational operators
Optional and any
(C++17)
(C++17)
Pairs and tuples
(C++11)
(C++17)
Swap, forward and move
(C++14)
(C++11)
(C++11)
Type operations
(C++11)
(C++17)
 
 
 
template <class Rep1, class Period1, class Rep2, class Period2>

struct common_type<std::chrono::duration<Rep1, Period1>,
                   std::chrono::duration<Rep2, Period2>> {
    typedef std::chrono::duration<
        typename std::common_type<Rep1, Rep2>::type, /*see note*/> type;

};
(since C++11)

Exposes the type named type, which is the common type of two std::chrono::durations.

[edit] Note

The period of the resulting duration is the greatest common divisor of Period1 and Period2.

std::common_type<> is specialized for std::chrono::duration.

[edit] Example

#include <iostream>
#include <chrono>
 
// std::chrono already finds the greatest common divisor,
// likely using std::common_type<>. We make the type
// deduction externally. 
 
template <typename T,typename S>
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() 
{
    typedef std::chrono::milliseconds milliseconds;
    typedef std::chrono::microseconds microseconds;
 
    auto ms = milliseconds(30);
    auto us = microseconds(1100);
 
    std::cout << ms.count() << "ms - " << us.count() << "us = " 
              << durationDiff(ms,us).count() <<  "\n";
}

Output:

30ms - 1100us = 28900

[edit] See also

(C++11)
deduces the result type of a mixed-mode arithmetic expression
(class template)