-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp_fixed_value.cpp
More file actions
109 lines (80 loc) · 1.96 KB
/
cpp_fixed_value.cpp
File metadata and controls
109 lines (80 loc) · 1.96 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
#include "static_value.h"
namespace internaltypes
{
struct myID;
struct myValue;
}
using MyID = StaticValue<unsigned int, internaltypes::myID>;
using MyValue = StaticValue<unsigned int, internaltypes::myValue>;
void IllegalCode()
{
// It must not be possible to compile this code
#ifdef COMPILE_BAD_CODE
// no assignment from POD; implicit construction
{
MyID myID = 123;
}
// no comparison with POD
{
MyID myID { 123 };
auto res = myID == 123;
}
// no assignment from other type
{
MyID myID { 123 };
MyValue myValue { 456 };
myID = myValue;
}
// no comparison with other type
{
MyID myID { 123 };
MyValue myValue { 456 };
auto res = myID == myValue;
}
// no arithmetic operations
{
MyID idA { 123 };
MyID idB { 123 };
auto res = idA + idB;
}
#endif
}
#include<iostream>
void CorrectUse()
{
MyID firstID { 123 };
MyID secondID { 456 };
// compare
const auto res = firstID != secondID;
if (res)
{
std::cout << "IDs are the same" << std::endl;
}
// assign new value
MyID thirdID { 0 };
thirdID = MyID { 789 };
std::cout << "ID: " << thirdID.GetValue() << std::endl;
}
void CompileTimeUnitTest()
{
constexpr MyID::DataType value = 123;
constexpr MyID idA { value };
// test value
constexpr auto gotValue = idA.GetValue();
constexpr auto testValue = gotValue == value;
static_assert(testValue, "StaticValue::GetValue() Failure");
// test equality/inequality
constexpr MyID idB { value };
constexpr auto testEquality = idA == idB;
static_assert(testEquality, "StaticValue Equality Failure");
constexpr MyID idC { 456 };
constexpr auto testInequality = idA != idC;
static_assert(testInequality, "StaticValue Inequality Failure");
}
int main()
{
IllegalCode();
CorrectUse();
CompileTimeUnitTest();
return 0;
}