Area operator for a base class in super multiple non-virtual inheritance

Consider this (completely unnecessary, but absolutely correct) class inheritance:

struct Area { int size; }; struct Pattern { int size; }; struct R : Area, Pattern {}; struct C : Area, Pattern {}; struct X: R , C {}; 

Let's look at the graph of this great hierarchy:

 Area Pattern |\ /| | \/ | | /\ | |/ \| RC \ / \/ X 

Now, if I'm not mistaken, X should have 4 size members.

How to access them using the scope operator?

The obvious solution does not work:

 X x; xR::Area::size = 24; 

clang error:

 23 : <source>:23:3: error: ambiguous conversion from derived class 'X' to base class 'Area': struct X -> struct R -> struct Area struct X -> struct C -> struct Area xR::Area::size = 8; ^ 1 error generated. 

Gcc error:

 <source>: In function 'auto test()': 23 : <source>:23:14: error: 'Area' is an ambiguous base of 'X' xR::Area::size = 8; ^~~~ 

Some necessary clarification:

  • I just messed around, it's not a real design

    • please do not indicate design problems
    • and please don’t think it is a good design. That ... not - at least
  • It is strictly about C ++ syntax to eliminate ambiguity.

    • please do not offer to do this.
    • please do not offer virtual inheritance.
+5
source share
1 answer

something like static_cast<R&>(x).Area::size = 8;

which is just as ugly as it should be :)

To find out why the source code does not work, it is worth mentioning that the qualified identifier has the form (among others) of type-name::id , so xR::Area::y equivalent to using T = R::Area; xT::y; using T = R::Area; xT::y; , which clearly does not help with respect to values.

+5
source

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


All Articles