用于安全整数转换的C ++模板 [英] C++ Template for safe integer casts

查看:92
本文介绍了用于安全整数转换的C ++模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个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吗?它是一个跨平台模板,将对各种整数类型进行整数溢出检查。可在codeplex使用

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 codeplex

  • http://www.codeplex.com/SafeInt

这篇关于用于安全整数转换的C ++模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆