用于安全整数转换的 C++ 模板

2023-09-26C/C++开发问题
1

本文介绍了用于安全整数转换的 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?它是一个跨平台模板,将对各种整数类型进行整数溢出检查.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

  • https://github.com/dcleblanc/SafeInt

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6