Library Documentation Index

Safe Numerics

PrevUpHomeNext

automatic

Description

This type contains the meta-functions to return a type with sufficient capacity to hold the result of a given binary arithmetic operation.

The standard C/C++ procedure for executing arithmetic operations on operands of different types is:

  • Convert operands to some common type using a somewhat elaborate elaborate rules defined in the C++ standard.

  • Execute the operation.

  • If the result of the operation cannot fit in the common type of the operands, discard the high order bits.

The automatic promotion policy replaces the standard C/C++ procedure for the following one:

  • Convert operands to some common type using to the following rules.

    • For addition. If the operands are both unsigned the common type will be unsigned. Otherwise it will be signed.

    • For subtraction, the common type will be signed.

    • For left/right shift, the sign of the result will be the sign of the left operand.

    • For all other types of operants, if both operands are unsigned the common type will be unsigned. Otherwise, it will be signed.

  • Determine the smallest size of the signed or unsigned type which can be guaranteed hold the result.

  • If this size exceeds the maximum size supported by the compiler, use the maximum size supported by the compiler.

  • Execute the operation.

    • Convert each operand to the common type.

    • If the result cannot be contained in the result type as above, invoke an error procedure.

    • Otherwise, return the result in the common type

This type promotion policy is applicable only to safe types whose base type is an Integer type.

Model of

PromotionPolicy

Example of use

The following example illustrates the automatic type being passed as a template parameter for the type safe<int>.

#include <boost/safe_numerics/safe_integer.hpp> 
#include <boost/safe_numerics/automatic.hpp>
 
int main(){
    using namespace boost::numeric;
    // use automatic promotion policy where C++ standard arithmetic 
    // might lead to incorrect results
    using safe_t = safe<std::int8_t, automatic>;

    // In such cases, there is no runtime overhead from using safe types.
    safe_t x = 127;
    safe_t y = 2;
    // z is guaranteed correct without any runtime overhead or exception.
    auto z = x + y; 
    return 0;
}
Header

#include <boost/numeric/safe_numerics/automatic.hpp>


PrevUpHomeNext