Method chaining

Method chaining is a borrowed C++ technique; it originates in Smalltalk. Its main purpose is to eliminate unnecessary local variables. You have used method chaining already, although you may not have realized it. Consider this code that you have probably written many times:

int i, j;
std::cout << i << j;

The last line invoked the inserter operator << twice. The first time it is invoked on the object on the left-hand side of the operator, std::cout. What object is the second call on? In general, the operator syntax is just a way to call a function named operator<<(). Usually, this particular operator is a non-member function, but the std::ostream class has several member function overloads as well, and one of them is for int values. So, the last line really is this:

std::cout.operator(i).operator<<(j);

The second call to operator<<() is done on the result of the first one. The equivalent C++ code is this:

auto& out1 = std::cout.operator(i);
out1.operator<<(j);

This is the method chaining—the call to one method function returns the object on which the next method should be called. In the case of std::cout, the member operator<<() returns a reference to the object itself. By the way, the non-member operator<<() does the same, only instead of the implicit argument this, it has the stream object as an explicit first argument (the difference will become much less visible in C++20 because of the universal calling syntax). 

Now, we can use method chaining to eliminate the explicitly named argument object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.33.207