Boost库中提供了一个安全数字类型的扩展库:boost::safe_numerics::cpp,它可以帮助我们更加安全地使用数字类型,在程序中预防溢出、下溢、除零错误等情况。下面是一个简单的测试程序,演示了如何在程序中使用boost::safe_numerics::cpp扩展库。
#include <iostream>
#include <boost/safe_numerics/safe_integer.hpp>
#include <boost/safe_numerics/exception.hpp>
namespace sn = boost::safe_numerics;
using safe_int = sn::safe<
int,
sn::native,
sn::trap_exception
>;
int main()
{
safe_int x = 10;
safe_int y = 20;
try
{
safe_int z = x + y; // 溢出
std::cout << "z = " << z << std::endl;
}
catch (sn::exception & ex)
{
std::cout << "Exception: " << ex.what() &