Namespaces
Variants

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

From cppreference.net
定义于头文件 <chrono>
template < class Rep1, class Period1, class Rep2, class Period2 >

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

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

公开名为 type 的类型,该类型是两个 std::chrono::duration 的公共类型,其周期为 Period1 Period2 的最大公约数。

目录

成员类型

成员类型 定义
type std:: chrono :: duration < typename std:: common_type < Rep1, Rep2 > :: type , /* 见注释 */ >

注释

结果持续时间的周期可以通过计算 Period1 :: num Period2 :: num 的最大公约数,同 Period1 :: den Period2 :: den 的最小公倍数之比得出。

示例

#include <chrono>
#include <iostream>
#include <type_traits>
// std::chrono 已能自动寻找最大公约数,
// 很可能使用了 std::common_type<>。我们在外部进行类型推导。
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';
}

输出:

30ms - 1100us = 28900us

参见

特化 std::common_type 特征
(类模板特化)
确定一组类型的公共类型
(类模板)