-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflag.cpp
167 lines (130 loc) · 2.01 KB
/
flag.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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#include <iostream>
typedef unsigned BitPos;
enum class FlagPos : BitPos
{
_0 = 0, _1 = 1, _2 = 2, _3 = 3, _4 = 4, _5 = 5, _6 = 6, _7 = 7
};
class Flag
{
public:
enum class State
{
_, O, I,
};
protected:
State state;
public:
Flag()
: state(State::_)
{
}
Flag(const bool x)
: state(x ? State::I : State::O)
{
}
virtual ~Flag()
{
}
void set(const bool x)
{
state = x ? State::I : State::O;
}
bool get() const
{
if (Flag::State::I == state)
{
return true;
}
if (Flag::State::O != state)
{
throw std::domain_error("flag is not inited");
}
return false;
}
};
class FlagBit : public Flag
{
protected:
FlagPos position;
public:
FlagBit(const FlagPos x, const bool y)
: Flag(y), position(x)
{
}
FlagBit(const FlagPos x)
: Flag(), position(x)
{
}
void setState(const Flag::State x)
{
state = x;
}
Flag::State getState() const
{
return state;
}
void set1()
{
state = Flag::State::I;
}
void set0()
{
state = Flag::State::O;
}
template<class T>
void apply(T &i)
{
const T mask = (static_cast<T>(1)) << (static_cast<BitPos>(position));
switch (state)
{
case Flag::State::O:
{
std::cout << "-" << ~mask << std::endl;
i &= ~mask;
}
break;
case Flag::State::I:
{
std::cout << "+" << mask << std::endl;
i |= mask;
}
break;
default:
{
throw std::domain_error("flag is not inited");
}
break;
}
}
};
int main(int vc, char *vp[])
{
std::cout << std::hex;
FlagBit f(FlagPos::_2);
if (f.getState() == Flag::State::_)
std::cout << "NUL";
else if (f.getState() == Flag::State::I)
std::cout << "ONE";
else if (f.getState() == Flag::State::O)
std::cout << "ZERO";
else
std::cout << "????";
std::cout << std::endl;
unsigned t = 0x9;
try
{
f.apply(t);
}
catch (const std::exception &e)
{
std::cout << e.what() << std::endl;
}
std::cout << t << std::endl;
f.set1();
f.apply(t);
std::cout << t << std::endl;
f.set0();
f.apply(t);
std::cout << t << std::endl;
return 0;
}