我实现了模板功能“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/