The Open-Closed Principle (OCP) means that code should be open for extension but closed for modification. Open for extension means that we could extend the list of types the code supports easily. Closed for modification means existing code shouldn't change, as this can often cause bugs somewhere else in the system. A great feature of C++ demonstrating this principle is operator<< of ostream. To extend it so that it supports your custom class, all you need to do is to write code similar to the following:
std::ostream &operator<<(std::ostream &stream, const MyPair<int, int>
&mp) {
stream << mp.firstMember() << ", ";
stream << mp.secondMember();
return stream;
}
Note that our implementation of operator<< is a free (non-member) function. You should prefer those to member functions if possible as it actually helps encapsulation. For more details on this, consult the article by Scott Meyers in the Further reading section at the end of this chapter. If you don't want to provide public access to some field that you wish to print to ostream, you can make operator<< a friend function, like so:
class MyPair {
// ...
friend std::ostream &operator<<(std::ostream &stream,
const MyPair &mp);
};
std::ostream &operator<<(std::ostream &stream, const MyPair &mp) {
stream << mp.first_ << ", ";
stream << mp.second_ << ", ";
stream << mp.secretThirdMember_;
return stream;
}
Note that this definition of OCP is slightly different from the more common one related to polymorphism. The latter is about creating base classes that can't be modified themselves, but are open for others to inherit from them.
Speaking of polymorphism, let's move on to the next principle as it is all about using it correctly.