Automatic two-phase init -- Krzysztof Ostrowski

Deferred initialisation for classes that inherit constructors, or Automatic two-phase init.

Deferred initialisation for classes that inherit constructors

by Krzysztof Ostrowski

From the article:

Constructor inheritance through using-declaration is a powerful technique that can be easily used to introduce pre-defined behaviour to custom types. As an example, consider a generic visitor design pattern implementation that is parametrised by the names of visitable types, and an unique tag that identifies given visitor template instance. Such an instance can be "mixed-in" into a custom type D by simply deriving from it... and inheriting its constructors to make it behave as it would be a Visitor template instance itself:

struct D
  : Visitor<
        A         // the tag
      , X, Y, Z   // "list" of visitable types
      >
{
    using Visitor::Visitor;
};
What if there is a need to run an "additional" initialisation code as it would be run in the D constructor if one were there? Bjarne Stroustrup suggests member-initializers that do half of a work we would like to do here. While direct member initialisation sets required initial values for all the members (except bit field members), it does not offer a direct way to execute custom code that makes use of those members, the custom code that typically resides in the constructor's body.
This article presents a solution that enables injection of a custom code to be executed once all the non-static members are initialised.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.