-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNamedParameterByThis.cpp
88 lines (74 loc) · 2.05 KB
/
NamedParameterByThis.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
/**
* \file NamedParameterByThis.cpp
* \brief Solve order of the parameters problem
*
* Change the function's parameters to methods of a newly created class, where all these methods
* return *this by reference. Then you simply rename the main function into a parameterless "do-it"
* method on that class
*
* When a function takes many parameters, the programmer has to remember the types and the order
* in which to pass them. Also, default values can only be given to the last parameters,
* so it is not possible to specify one of the later parameters and use the default value
* for former ones. Named parameters let the programmer pass the parameters to a function in any
* order and they are distinguished by a name. So the programmer can explicitly pass all the needed
* parameters and default values without worrying about the order used in the function declaration.
*/
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//--------------------------------------------------------------------------------------------------
class X
{
public:
// non-const function
X &
setA(const int i)
{
_a = i;
return *this;
}
// non-const function
X &
setB(const char c)
{
_b = c;
return *this;
}
static
X construct()
{
return X();
}
private:
int _a {};
char _b {};
// Initialize with default values, if any.
X() :
_a{-999},
_b{'C'}
{
}
friend
std::ostream &operator << (std::ostream &os, const X &x);
};
//-------------------------------------------------------------------------------------------------
std::ostream &
operator << (std::ostream &os, const X &x)
{
os
<< "{" << x._a << ", " << x._b << "}";
return os;
}
//--------------------------------------------------------------------------------------------------
int main(int, char **)
{
const auto &x = X::construct()
.setA(10)
.setB('Z');
std::cout << STD_TRACE_VAR(x) << std::endl;
return EXIT_SUCCESS;
}
//--------------------------------------------------------------------------------------------------
#if OUTPUT
x: {10, Z}
#endif