-
Notifications
You must be signed in to change notification settings - Fork 1
/
decimal.tcc
45 lines (39 loc) · 861 Bytes
/
decimal.tcc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#define decimal_tcc
#include <stdexcept>
#include "decimal.h"
namespace kaiu {
template <typename T, typename>
decimal::decimal(T val)
{
if (val < 0) {
throw std::invalid_argument("Negative value not allowed");
}
digits.reserve(int(std::numeric_limits<T>::digits10 + 1));
if (val) {
while (val) {
digits.push_back(val % 10);
val /= 10;
}
} else {
digits.push_back(0);
}
}
template <typename T, typename>
decimal::operator T() const
{
const T max = std::numeric_limits<T>::max();
T r = 0;
for (auto digit = digits.crbegin(); digit != digits.crend(); ++digit) {
if ((max - *digit) / 10 < r) {
throw std::overflow_error("Overflow in conversion to fixed-width integer");
}
r = (r * 10) + *digit;
}
return r;
}
template <typename T, typename>
bool decimal::operator ==(const T& b) const
{
return operator ==(decimal(b));
}
}