forked from goldshtn/cool-cpp-things
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunits.h
More file actions
125 lines (108 loc) · 3.03 KB
/
units.h
File metadata and controls
125 lines (108 loc) · 3.03 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#ifndef COOL_THINGS_UNITS_H
#define COOL_THINGS_UNITS_H
#include <iostream>
#include "intvector.h"
namespace units
{
template <typename IntVector>
struct unit
{
double value_;
unit(double v) : value_(v)
{ }
double value() const
{ return value_; }
};
template <typename IntVector>
unit<IntVector> operator+(unit<IntVector> u1, unit<IntVector> u2)
{
return u1.value() + u2.value();
}
template <typename IntVector>
unit<IntVector> operator-(unit<IntVector> u1, unit<IntVector> u2)
{
return u1.value() - u2.value();
}
template <typename IntVector1, typename IntVector2>
unit<typename intvector_add<IntVector1, IntVector2>::type>
operator*(
unit<IntVector1> u1,
unit<IntVector2> u2)
{
return u1.value() * u2.value();
}
template <typename IntVector1, typename IntVector2>
unit<typename intvector_subtract<IntVector1, IntVector2>::type>
operator/(
unit<IntVector1> u1,
unit<IntVector2> u2)
{
return u1.value() / u2.value();
}
template <int Mass, int Time, int Length>
using system = intvector<Mass, Time, Length>;
using scalar = unit<system<0, 0, 0>>;
using mass = unit<system<1, 0, 0>>;
using time = unit<system<0, 1, 0>>;
using distance = unit<system<0, 0, 1>>;
using speed = unit<system<0, -1, 1>>; // meters per second
using acceleration = unit<system<0, -2, 1>>; // meters per second per second
void symbol_sequence(std::ostream& os, std::initializer_list<std::pair<int, std::string>> seq)
{
bool first = true;
for (auto const& p : seq)
{
if (p.first > 0)
{
if (!first)
os << " * ";
os << p.second;
if (p.first > 1)
{
os << "^" << p.first;
}
first = false;
}
}
first = true;
for (auto const& p : seq)
{
if (p.first < 0)
{
if (first)
os << " / ";
if (!first)
os << " * ";
os << p.second;
if (p.first < 1)
{
os << "^" << -p.first;
}
first = false;
}
}
}
template <int Mass, int Time, int Length>
std::ostream& operator<<(std::ostream& os, unit<system<Mass, Time, Length>> u)
{
os << u.value() << " ";
symbol_sequence(os, {{Mass, "kg"},{Time, "s"},{Length,"m"}});
return os;
}
inline namespace literals
{
mass operator "" _kg(long double kg)
{
return mass(kg);
}
distance operator "" _m(long double m)
{
return distance(m);
}
time operator "" _s(long double s)
{
return time(s);
}
}
} // namespace units
#endif //COOL_THINGS_UNITS_H