General method chaining
Applications of method chaining in C++ are not limited to argument passing (we have already seen another application, although a well-hidden one, in the form of streaming I/O). For use in other contexts, it is helpful to consider some more general forms of method chaining.
Method chaining versus method cascading
The term method cascading is not often found in the context of C++, and for a good reason—C++ does not really support it. Method cascading refers to calling a sequence of methods on the same object. For example, in Dart, where method cascading is supported explicitly, we can write the following:
var opt = Options(); opt.SetA()..SetB();
This code first calls SetA()
on the opt object, then calls SetB()
on the same object. The equivalent code is this:
var opt = Options(); opt.SetA() opt.SetB();
But wait, did we not just do the same with C++ and our options object? We did, but we skimmed over an important difference. In method chaining...