-
Notifications
You must be signed in to change notification settings - Fork 160
/
explicit.cpp
92 lines (74 loc) · 1.78 KB
/
explicit.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
/*
# explicit keyword
Keyword specifies that a given constructor can only be used explicitly.
*/
#include "common.hpp"
class Implicit {
public:
int i;
Implicit(int i) : i(i) {}
operator int() {
return this->i;
}
};
class Implicit2 {
public:
int i;
Implicit2(Implicit i) : i(i) {}
};
class Explicit {
public:
int i;
explicit Explicit(int i) : i(i) {}
// TODO this makes no sense right, since it is not a ctor that takes a single arg?
// why does it compile without warning
explicit Explicit(int i, int j) : i(i + j) {}
// ERROR: only for constructors and conversion functions since C++11.
//explicit void method(){}
#if __cplusplus >= 201103L
explicit operator int() {
return this->i;
}
// Cannot do this test here as the `int i = o` would then use it.
//operator float() {
//return (float)this->i;
//}
#endif
};
int main() {
// Without implicit, the cast is made with the constructor that takes one argument.
{
Implicit o = 1;
assert(o.i == 1);
}
// ERROR: Only a single cast can be made.
//{ Implicit2 o = 1; }
{
Implicit2 o = Implicit(1);
assert(o.i == 1);
}
// ERROR: explicit prevents implicit casts.
//{ Explicit o = 1; }
// Explicit casts are still allowed.
{
Explicit o = (Explicit)1;
assert(o.i == 1);
}
// Operator
{
{
Explicit o(1);
// ERROR
//int i = o;
}
{
Explicit o(1);
int i = (int)o;
}
{
Implicit o(1);
int i = o;
assert(i == 1);
}
}
}