Boost C++ Idioms
This time lets take a brief look at some nifty C++ idioms in the Boost peer-reviewed libraries. We will talk about Boost Base-from-Member idiom, Boost Safe bool idiom, Boost Named External Argument idiom, Boost Non-member get() idiom, Boost Meta-function wrapper idiom, Boost Iterator pair idiom, and the Boost Mutant idiom.This idiom is used to initialize a base class from a data-member of the derived class. It sounds contradictory to the rules of C++ language and that is the reason why this idiom is present. It basically boils down to pushing the parameter data member in a private base class and put that private base class before the dependent base class in the derivation order. A generalization of the technique can be found here.
Many authors have talked about the evils of type conversion functions defined in a class. Such functions allow the objects of that type to participate in nonsensical expressions. One good example is in standard C++:
std::cout << std::cin << std::cerr; // Compiles just fine!
The safe bool idiom invented by Peter Dimov eliminates these problems. It is used in std::auto_ptr, boost::shared_ptr. Bjorn Karlsson, the author of the book Beyond the C++ Standard Library, tell us about this nifty technique called the safe bool idiom in his article on Artima.
It is a technique to pass parameters to included header files! Quickest way to learn about this idiom is to read this one paragraph.
In Cheshire Cat idiom or pimpl like idioms, accessing non-const functions of the pointee wrapped inside a const wrapper object is a problem. I discussed a technique to have const-overloaded arrow operator to avoid such an accident. This is important because the user of the wrapper does not (and should not) know that it is in-fact using pimpl idiom. The Boost non-member get() idiom deals with the same problem, albeit differently, in the context of value_initialized objects. It also used const-overloaded versions of get() functions.
The compilers that don't support template template parameters, meta-function wrapper (a.k.a. Policy Clone idiom) is useful to instantiate a clone of template parameter. Essentially, it says, "I don't know what type you are, and I don't know how you were parameterized, but I want an exact clone of you, which is parameterized with type T (T is known)."
Note that it is one rare place where we have to use both the keywords typename and template in the typedef. For compilers that support template template parameters, there is no need to use this idiom. Arguably this idiom is more general than template template parameters.
Not much information other than simple googling is available about the remaining two idioms: Boost Iterator pair idiom and Boost Mutant idiom. Any inputs are more than welcome!