-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathcast_operator.cpp
More file actions
42 lines (33 loc) · 792 Bytes
/
cast_operator.cpp
File metadata and controls
42 lines (33 loc) · 792 Bytes
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
/*
Allows to convert objects to primitives and other objects.
http://en.cppreference.com/w/cpp/language/cast_operator
*/
#include "common.hpp"
class ToInt {
public:
int i;
ToInt(int i) : i(i) {}
operator int() {
return this->i;
}
};
class ToToInt {
public:
int i;
ToToInt(int i) : i(i) {}
operator ToInt() {
return ToInt(this->i);
}
};
int main() {
// Explicit cast.
assert((int)ToInt(0) == 0);
// Implicit conversion.
assert(ToInt(0) == 0);
// ERROR: Only a single implicit cast is possible at a time.
//assert(ToToInt(0) == 0);
// OK, on implicit cast.
assert((ToInt)ToToInt(0) == 0);
// OK, all explicit.
assert((int)(ToInt)ToToInt(0) == 0);
}