template <typename T, T M = 0>
inline bool AheadOf(T a, T b) {
// 必须为无符号数
static_assert(std::is_unsigned<T>::value,
"Type must be an unsigned integer.");
return a != b && AheadOrAt<T, M>(a, b);
}
- 比较 a 和 b 的顺序
- b 排在 a 前面,返回真,否则假
template <typename T, T M>
inline typename std::enable_if<(M == 0), bool>::type AheadOrAt(T
a, T b) {
static_assert(std::is_unsigned<T>::value,
"Type must be an unsigned integer.");
const T maxDist = std::numeric_limits<T>::max() / 2 + T(1);
// 规定特殊情况
if (a - b == maxDist)
return b < a;
// 调用顺序有调换
return ForwardDiff(b, a) < maxDist;
}
template <typename T, T M>
inline typename std::enable_if<(M == 0), T>::type ForwardDiff(T a, T b) {
static_assert(std::is_unsigned<T>::value,
"Type must be an unsigned integer.");
// 调用顺序调换,使用AheadOrAt参数 实际调用是 a-b
return b - a;
}
使用AheadOrAt
中的 a,b 定义
T 默认为 uint16_t 类型,maxDist = 32768
- a=1000, b = 1001 => a - b = -1, 转换为 uint16_t 为 65535, 大于 maxDist,return false => a 是比 b 更老的包
- a=1001, b = 1000 => a - b = 1, 转换为 uint16_t 为 1, 小于 maxDist,return true => a 是比 b 更新的包
- a=1, b=65534 => a - b = -65533,转换为 uint16_t 为 3,小于 maxDist,return true
- a=65534, b=1 => a - b = 65533,转换为 uint16_t 为 65533,大于 maxDist,return false
5533,转换为 uint16_t 为 65533,大于 maxDist,return false