c++ - C++模板将如何处理溢出?

标签 c++ templates types overflow

我实现了模板功能“clamp”,因为我的项目不支持C++ 20。

template<typename T>
constexpr const T clamp(const T& value, const T& lo, const T& hi)
{
    return static_cast<T>(std::min(std::max(lo, value), hi));
}
我使用它以以下方式检查溢出。
if (adcVal > clamp<uint16_t>((adcHi + voltageThreshold), adcHi, std::numeric_limits<uint16_t>::max()))
{
    //voltage has jumped past required threshold. 
}
是否保证溢出值将保留为uint16_t

最佳答案

Is there a guarantee that overflow value will remain as a uint16_t?


我怀疑您的意思是adcHi + voltageThreshold中溢出。我假设操作数是uint16_t
不,没有这样的保证。在典型系统上,uint16_t操作数将首先提升为int,结果也将变为int。并且总和可能超出uint16_t的可表示值。
当然,将加法的结果传递给uint16_t后,一旦将其转换为clamp,就可以保证是uint16_t
std::numeric_limits::max()传递给钳制将意味着输入将不会从上限被钳制,因为它永远不会大于限制。

How will a C++ template handle overflow?


溢出发生在调用功能模板之前。

关于c++ - C++模板将如何处理溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63158106/

相关文章:

c++ - 模板特化示例

c++ - 模板函数的参数不进行任何隐式转换

c++ - 子类化和添加数据成员

c++ - 为模板类重载运算符<<

ios - @encoding 类型 id 其中 id 实际上是任何对象

types - 两条记录的两个字段在 OCaml 中具有相同的标签

python - 确定对象的类型?

c++ - 在 #define 的开头使用下划线作为包含守卫

c++ - GDI Sprite 显示一段时间后消失

c++ - 队列类 C++ 的输出运算符重载