bux API Reference 1.9.0
Static library of whatever are seen required in general purpose but not directly supported from Modern C++. Or whatever reusable originated from my side projects.
Loading...
Searching...
No Matches
SafeArith.h
Go to the documentation of this file.
1#pragma once
2
3#include <limits> // std::numeric_limits<>
4
5namespace bux {
6
7//
8// Types
9//
10namespace Helper_ {
11
12template<bool FLAG_signed, class T>
14{
15 static T add(T a, T b);
16};
17
18template<bool FLAG_integer, bool FLAG_signed, bool FLAG_overflow, class T>
20{
21 static inline int cast(T a)
22 { return a < T()? -1: a > T() ?1: 0; }
23};
24
25} // namespace Helper_
26
27//
28// Function Templates
29//
30template<class T>
31inline T addNoWrap(T a, T b)
32{
34}
35
36template<class T>
37inline int compareReturn(T a)
38{
39 return Helper_::C_CmpRet<
40 std::numeric_limits<T>::is_integer,
41 std::numeric_limits<T>::is_signed,
42 (std::numeric_limits<T>::radix == std::numeric_limits<int>::radix &&
43 std::numeric_limits<T>::digits > std::numeric_limits<int>::digits),
44 T>::cast(a);
45}
46
47//
48// Specialize class templates
49//
50namespace Helper_ {
51
52template<class T>
53struct C_NoWrap<true,T>
54{
55 static T add(T a, T b)
56 {
57 const bool aneg =a < T();
58 const bool bneg =b < T();
59 if (aneg != bneg)
60 return T(a +b);
61
62 if (aneg)
63 return std::numeric_limits<T>::min() -a < b? T(a +b):
64 std::numeric_limits<T>::min();
65
66 // a == 0 || b == 0 is considered a rare case
67 return std::numeric_limits<T>::max() -a > b? T(a +b):
68 std::numeric_limits<T>::max();
69 }
70};
71
72template<class T>
73struct C_NoWrap<false,T>
74{
75 static T add(T a, T b)
76 {
77 return T(std::numeric_limits<T>::max() -a) > b? T(a +b):
78 std::numeric_limits<T>::max();
79 }
80};
81
82template<bool FLAG_signed, class T>
83struct C_CmpRet<true,FLAG_signed,false,T>
84{
85 static inline int cast(T a)
86 { return int(a); }
87};
88
89template<bool FLAG_integer, bool FLAG_overflow, class T>
90struct C_CmpRet<FLAG_integer,false,FLAG_overflow,T>
91{
92 static inline int cast(T a)
93 { return a != T()? 1: 0; }
94};
95
96} // namespace Helper_
97
98} //namespace bux
THE common namespace of bux library.
Definition AtomiX.cpp:3
int compareReturn(T a)
Definition SafeArith.h:37
T addNoWrap(T a, T b)
Definition SafeArith.h:31
static int cast(T a)
Definition SafeArith.h:21
static T add(T a, T b)