Scope operator for base class in super multiple non-virtual inheritance

五迷三道 提交于 2021-02-07 14:22:21

问题


Consider this (completely non-nonsensical, but perfectly valid) class inheritance:

struct Area { int size; };
struct Pattern { int size; };

struct R : Area, Pattern {};
struct C : Area, Pattern {};

struct X: R , C {};

Let's see a graph of this great hierarchy:

Area  Pattern
  |\  /|   
  | \/ |
  | /\ |  
  |/  \|
  R    C
   \  /
    \/
    X

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

How to refer to them using the scope operator?

The obvious solution doesn't work:

X x;
x.R::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
  x.R::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'
   x.R::Area::size = 8;
              ^~~~

Some much needed clarification:

  • I was just messing around, it is not a real design

    • so please don't point the problems with the design
    • and please don't think this is a good design. It is... not - to say the least
  • This is strictly about the C++ syntax to resolve the ambiguity.

    • please don't suggest to not do it
    • please don't suggest virtual inheritance.

回答1:


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

which is as ugly as it should be :)

To clarify why the original code doesn't work, it's worth mentioning that a qualified id has the form (among others) type-name::id so x.R::Area::y is equivalent to using T = R::Area; x.T::y; that clearly does not help as far as disambiguation is concerned.



来源:https://stackoverflow.com/questions/46648905/scope-operator-for-base-class-in-super-multiple-non-virtual-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!