forked from andreasfertig/cppinsights
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsightsOnce.h
60 lines (53 loc) · 1.06 KB
/
InsightsOnce.h
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
#ifndef INSIGHTS_ONCE_H
#define INSIGHTS_ONCE_H
namespace clang::insights {
/// \brief A helper object which returns a boolen value just once and toggles it after the first query.
///
/// This allows to simplify code like this:
/// \code
/// bool first{true};
/// for(... : ...) {
/// if(first) {
/// first = false;
/// ...
/// } else {
/// ...
/// }
/// \endcode
///
/// into this:
/// \code
/// OnceTrue first{};
/// for(... : ...) {
/// if(first) {
/// ...
/// } else {
/// ...
/// }
/// \endcode
template<bool VALUE>
class Once
{
public:
Once() = default;
Once(bool value)
: mValue{value}
{
}
operator bool()
{
if(VALUE == mValue) {
mValue = not VALUE;
return VALUE;
}
return not VALUE;
}
private:
bool mValue{VALUE};
};
/// Returns true only once, following checks return false.
using OnceTrue = Once<true>;
/// Returns false only once, following checks return true.
using OnceFalse = Once<false>;
} // namespace clang::insights
#endif /* INSIGHTS_ONCE_H */