Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

Library Documentation Index

Safe Numerics

PrevUpHomeNext

safe_signed_literal<Value, PP , EP> and safe_unsigned_literal<Value, PP, EP>

Description
Associated Types
Template Parameters
Model of
Inherited Valid Expressions
Example of use
make_safe_literal(n, PP, EP)
Header

Description

A safe type which holds a literal value. This is required to be able to initialize other safe types in such a way that an exception code is not generated. It is also useful when creating constexpr versions of safe types. It contains one immutable value known at compile time and hence can be used in any constexpr expression.

Associated Types

PP A type which specifies the result type of an expression using safe types.
EP A type containing members which are called when a correct result cannot be returned

Template Parameters

Parameter Type Requirements Description
Value Integer value used to initialize the literal
PP PromotionPolicy<PP>

Optional promotion policy. Default value is void

EP Exception Policy<EP>

Optional exception policy. Default value is void

Model of

Numeric

Integer

Inherited Valid Expressions

safe literal types are immutable. Hence they only inherit those valid expressions which don't change the value. This excludes assignment, increment, and decrement and all unary operators except unary -, + and ~. Other than that, they can be used anywhere a Value type can be used. Note that the default promotion and exception policies are void. This is usually convenient since when a safe literal is used in a binary operation, this will inherit the policies of the other type. On the other hand, this can be inconvenient when operands of a binary expression are both safe literals. This will fail to compile since there are no designated promotion and exception policies. The way to address this to assign specific policies as in this example.

template<typename T>
using compile_time_value = safe_signed_literal<T>;

constexpr compile_time_value<1000> x;
constexpr compile_time_value<0> y;

// should compile and execute without problem
    
std::cout << x << '\n';

// all the following statements should fail to compile because there are 
// no promotion and exception policies specified.
constexpr safe<int> z = x / y;

Example of use

#include <boost/safe_numerics/safe_integer_literal.hp>

constexpr boost::safe_numerics::safe_signed_literal<42> x;

make_safe_literal(n, PP, EP)

This is a macro which returns an instance of a safe literal type. This instance will hold the value n. The type of the value returned will be the smallest safe type which can hold the value n.

Header

#include <boost/safe_numerics/safe_integer_literal.hpp>


PrevUpHomeNext