-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBool.cpp
More file actions
86 lines (71 loc) · 2.07 KB
/
Bool.cpp
File metadata and controls
86 lines (71 loc) · 2.07 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
/**
* \file Bool.cpp
* \brief Conversion operator bool
*
* explicit help protect against unwanted conversion while assigning it
*
* \see https://stackoverflow.com/questions/4600295/what-is-the-meaning-of-operator-bool-const
* https://www.modernescpp.com/index.php/c-core-guidelines-more-rules-to-overloading/
*/
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//--------------------------------------------------------------------------------------------------
struct A
/// Non-explicit conversion
{
operator bool() const
{
return true;
}
};
//-------------------------------------------------------------------------------------------------
struct B
/// Explicit conversion
{
explicit operator bool() const
{
return true;
}
};
//--------------------------------------------------------------------------------------------------
int main(int, char **)
{
// Non-explicit conversion
{
A a;
if (a) {
std::cout << "a: true" << std::endl; // OK: A::operator bool()
}
const bool res1 = a; // OK: copy-initialization selects A::operator bool()
const bool res2 = static_cast<bool>(a); // OK: static_cast performs direct-initialization
std::cout << STD_TRACE_VAR(res1) << std::endl;
std::cout << STD_TRACE_VAR(res2) << std::endl;
std::cout << STD_TRACE_VAR(!!res2) << std::endl;
std::cout << std::endl;
}
// Explicit conversion
{
B b;
if (b) {
std::cout << "b: true" << std::endl; // OK: B::operator bool()
}
// const bool res1 = b; // error: copy-initialization does not consider B::operator bool()
const bool res2 = static_cast<bool>(b); // OK: static_cast performs direct-initialization
// std::cout << STD_TRACE_VAR(res1) << std::endl;
std::cout << STD_TRACE_VAR(res2) << std::endl;
std::cout << STD_TRACE_VAR(!!res2) << std::endl;
std::cout << std::endl;
}
return EXIT_SUCCESS;
}
//--------------------------------------------------------------------------------------------------
#if OUTPUT
a: true
res1: 1
res2: 1
!!res2: 1
b: true
res2: 1
!!res2: 1
#endif