changes to implement the following:

a) made trap_exception work
b) updated manual and examples to show how to use library to eliminate runtime penalty
c) added in safe_literal
d) made corrections of various types
This commit is contained in:
Robert Ramey
2015-12-21 23:14:06 -08:00
parent cd620a8ec5
commit 1bc0b94e65
56 changed files with 1698 additions and 1739 deletions

View File

@@ -12,28 +12,30 @@ using namespace boost::numeric; // for safe_literal
// create a type for holding small integers. We "know" that C++ type
// promotion rules will work such that operations on this type
// will never overflow. If change the program to break this, the
// trap_exception will prevent compilation
// usage of the trap_exception promotion policy will prevent compilation.
using safe_t = safe_signed_range<
-24,
82,
native, // we don't need automatic in this case
trap_exception
native, // C++ type promotion rules work OK for this example
trap_exception // catch problems at compile time
>;
int f(const safe_t & x, const safe_t & y){
int z = x + y; // we know that this cannot fail
// std::int8_t z = x + y; // but this COULD fail. So we get a compile error
std::cout << "(x + y)" << safe_format(x + y) << std::endl;
std::cout << "(x - y)" << safe_format(x - y) << std::endl;
auto f(const safe_t & x, const safe_t & y){
//safe_t z = x + y; // depending on values of x & y COULD fail
auto z = x + y; // due to C++ type promotion rules,
// we know that this cannot fail
std::cout << "(x + y) = " << safe_format(x + y) << std::endl;
std::cout << "(x - y) = " << safe_format(x - y) << std::endl;
return z;
}
int main(int argc, const char * argv[]){
std::cout << "example 83:\n";
safe_t x(safe_literal<1>{}); // note special type for initialization needed
safe_t y(safe_literal<2>{}); // to avoid runtime penalty
std::cout << "x" << safe_format(x) << std::endl;
std::cout << "y" << safe_format(y) << std::endl;
std::cout << "z" << safe_format(f(x, y)) << std::endl;
// constexpr const safe_t z = 3; // fails to compile
const safe_t x(safe_literal<2>{});
const safe_t y = safe_literal<2>(); // to avoid runtime penalty
std::cout << "x = " << safe_format(x) << std::endl;
std::cout << "y = " << safe_format(y) << std::endl;
std::cout << "z = " << safe_format(f(x, y)) << std::endl;
return 0;
}