-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ex16_41_sum.cpp
92 lines (77 loc) · 2.78 KB
/
ex16_41_sum.cpp
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <climits>
#include <iostream>
template <typename T> struct promote;
template <> struct promote<short int> {
using type = int;
};
template <> struct promote<unsigned short int> {
using type = unsigned int;
};
template <> struct promote<int> {
using type = long long int;
};
template <> struct promote<unsigned int> {
using type = unsigned long int;
};
template <> struct promote<long int> {
using type = long long int;
};
template <> struct promote<unsigned long int> {
using type = unsigned long int;
};
template <> struct promote<long long int> {
using type = unsigned long long int;
};
template <> struct promote<unsigned long long int> {
using type = unsigned long long int;
};
template <> struct promote<float> {
using type = double;
};
template <> struct promote<double> {
using type = long double;
};
template <> struct promote<long double> {
using type = long double;
};
template <typename T> using promote_t = typename promote<T>::type;
template <typename T> auto sum(T lhs, T rhs) -> promote_t<T>
{
return static_cast<promote_t<T>>(lhs) + rhs;
}
int main()
{
std::cout << sum(std::numeric_limits<short int>::max(),
std::numeric_limits<short int>::max())
<< std::endl;
std::cout << sum(std::numeric_limits<unsigned short int>::max(),
std::numeric_limits<unsigned short int>::max())
<< std::endl;
std::cout << sum(std::numeric_limits<int>::max(),
std::numeric_limits<int>::max())
<< std::endl;
std::cout << sum(std::numeric_limits<unsigned int>::max(),
std::numeric_limits<unsigned int>::max())
<< std::endl;
std::cout << sum(std::numeric_limits<long int>::max(),
std::numeric_limits<long int>::max())
<< std::endl;
std::cout << sum(std::numeric_limits<unsigned long int>::max(),
std::numeric_limits<unsigned long int>::max())
<< std::endl;
std::cout << sum(std::numeric_limits<long long int>::max(),
std::numeric_limits<long long int>::max())
<< std::endl;
std::cout << sum(std::numeric_limits<unsigned long long int>::max(),
std::numeric_limits<unsigned long long int>::max())
<< std::endl;
std::cout << sum(std::numeric_limits<float>::max(),
std::numeric_limits<float>::max())
<< std::endl;
std::cout << sum(std::numeric_limits<double>::max(),
std::numeric_limits<double>::max())
<< std::endl; // too large
std::cout << sum(std::numeric_limits<long double>::max(),
std::numeric_limits<long double>::max())
<< std::endl; // too large
}