我正在尝试编写一个 C++ 模板函数,它将在整数溢出时引发运行时异常,该函数在不同整数类型、不同宽度和可能的有符号/无符号不匹配之间进行转换.出于这些目的,我不关心从浮点类型到整数类型的转换,也不关心其他对象到对象的转换.我想这样做而不必编写大量特殊情况代码.这是我目前拥有的:
I am trying to write a C++ template function that will throw a runtime exception on integer overflow in casts between different integral types, with different widths, and possible signed/unsigned mismatch. For these purposes I'm not concerned with casting from floating-point types to integral types, nor other object-to-object conversions. I'd like to do this without having to write lots of special case code. This is what I currently have:
template< typename T, typename R > void safe_cast( const T& source, R& result )
{
// get the maximum safe value of type R
R rMax = (R) ~0;
if ( rMax < 0 ) // R is a signed type
{
// assume that we're on an 8-bit twos-compliment machine
rMax = ~( 0x80 << ( ( sizeof( R ) - 1 ) * 8 ) );
}
if ( ( source & rMax ) != source )
{
throw new IntegerOverflowException( source );
}
result = static_cast<R>( source );
}
这是否正确且有效?
由于各种原因 stl 不可用,所以我不能使用 std::numeric_limits,而 Boost 中的任何东西都是正确的.
For various reasons stl isn't available, so I can't use std::numeric_limits, and anything from Boost is right out.
您是否尝试过 SafeInt?它是一个跨平台模板,将对各种整数类型进行整数溢出检查.github上已经有
Have you tried SafeInt? It's a cross platform template that will do integer overflow checks for a variety of integer types. It's available on github
这篇关于用于安全整数转换的 C++ 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!