Explanation of the Stroustrup Class Hierarchy Example

In the Stroustrup C ++ programming language (4th ed.), Section 27.4.2 shows a method for โ€œlinearizingโ€ the diamond class hierarchy to avoid the overhead of virtual base classes. He starts with a diamond drawing from a real project ( Bar Code Analysis Tool ):

enter image description here

The linear version is drawn as:

enter image description here

and

enter image description here

Code Scheme:

namespace ipr { struct Node { ... }; struct Expr : Node { ... }; struct Stmt : Expr { ... }; struct Decl : Stmt { ... }; struct Var : Decl { ... }; namespace impl { template<class T> struct Node : T { ... }; template<class T> struct Expr : Node<T> { ... }; template<class S> struct Stmt : S { ... }; template<class D> struct Decl : Stmt<Expr<D>> { ... }; struct Var : Decl<ipr::Var> { ... }; } } 

The irregular structure confuses me. Based on the original description, I expected impl to look something like this:

 namespace impl { template<class T> struct Node : T { ... }; template<class T> struct Expr : Node<T> { ... }; template<class S> struct Stmt : Expr<S> { ... }; template<class D> struct Decl : Stmt<D> { ... }; struct Var : Decl<ipr::Var> { ... }; } 

And I think the complete diagram of these classes is:

enter image description here

My question is , why don't the "internal" three impl template templates have parallel forms, as in my version of the code?

+5
source share
1 answer

My best guess is related to viewing the actual summary code that has

 template<class D> struct Decl : Stmt<Node<D>> { ... }; 

instead of Stroustrup's

 template<class D> struct Decl : Stmt<Expr<D>> { ... }; 

This suggests that impl::Stmt does not necessarily follow from impl::Expr in the end, as in the original diamond diagram (although it does come from the ipr::Expr ). This does not come from impl::Expr for Decl and Var , but for other implementation classes such as impl::For :

 struct For : Stmt<Expr<ipr::For> > { ... } 

I'm not sure why Straustrup did not explain the irregularity. Maybe he thought he removed it by changing Stmt<Node> to Stmt<Expr> , or maybe he didn't change it at all (that is, the code changed after he copied it), and he wanted leave it as is without explaining every detail.

Hope the best answer will explain this.

+2
source

Source: https://habr.com/ru/post/1211381/


All Articles