C++ Template for safe integer casts(用于安全整数转换的 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++ 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于安全整数转换的 C++ 模板


基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01