我正在尝试编写一个C++模板函数,它将在不同整数类型之间的转换中抛出整数溢出的运行时异常,具有不同的宽度,以及可能的有符号/无符号不匹配.出于这些目的,我不关心从浮点类型转换为整数类型,也不关心其他对象到对象的转换.我想这样做而不必写很多特殊的案例代码.这就是我目前拥有的:
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 ) …Run Code Online (Sandbox Code Playgroud)