Multiple inheritance + virtual function mess

后端 未结 6 785
灰色年华
灰色年华 2020-12-02 23:50

I have a diamond multiple inheritance scenario like this:

    A
  /   \\
 B     C
  \\   /
    D

The common parent, A, defines a virtual fu

相关标签:
6条回答
  • 2020-12-03 00:07

    You might want to look at Loki TypeLists if you really need to be able to track ancestry and enumerate through types. I'm not sure if what you are asking for is really possible without a bunch of work. Make sure that you aren't over-engineering here.

    On a slightly different note, if you are going to use MI in this manner (i.e., the dreaded diamond), then you should be very explicit about which virtual member you want. I can't think of a good case where you want to choose the semantics of B::fn() over C::fn() without explicitly making a decision when writing D. You will probably pick one over the other (or even both) based on what the individual method does. Once you have made a decision, the requirement is that inherited changes do not change the expectations or semantic interface.

    If you are really worried about swapping in a new class, say E in place of say B where E does not descend from B but offers the same interface, then you should really use the template approach though I'm not sure why there is a static_cast<> in there...

    struct A {
        virtual ~A() {}
        virtual void f() = 0;
    };
    struct B: A {
        virtual void f() { std::cout << "B::f()" << std::endl; }
    };
    struct C: A {
        virtual void f() { std::cout << "C::f()" << std::endl; }
    };
    
    template <typename Base1, typename Base2>
    struct D: Base1, Base2 {
        void g() { Base1::f(); Base2::f(); }
    };
    
    int main() {
        D<B,C> d1;
        D<C,B> d2;
        d1.g();
        d2.g();
        return 0;
    }
    
    // Outputs:
    //   B::f()
    //   C::f()
    //   C::f()
    //   B::f()
    

    works fine and seems a little easier to look at.

    0 讨论(0)
  • 2020-12-03 00:08

    You cannot enumerate the definitions of fn() in the ancestry. C++ lacks reflection. The only way I can imagine is a giant loop testing the typeid's of all possible ancestors. And it hurts to imagine that.

    0 讨论(0)
  • 2020-12-03 00:23

    There are already several questions that deal with this. Seems like we're running out of questions to ask. Maybe the search box should be bigger than the Ask Question button.

    See

    • How can I avoid the Diamond of Death when using multiple inheritance?
    • What is the exact problem with multiple inheritance?
    • Is Multiple Inheritance Evil?
    0 讨论(0)
  • 2020-12-03 00:28

    Unless you overwrite fn again in D, no it is not possible. Because there is no final overrider in a D object: Both C and B override A::fn. You have several options:

    • Drop either C::fn or B::fn. Then, the one that still overrides A::fn has the final overrider.
    • Place a final overrider in D. Then, that one overrides A::fn aswell as fn in C and B.

    For example the following results in a compile time error:

    #include <iostream>
    
    class A {
    public:
        virtual void fn() { }
    };
    
    class B : public virtual A {
    public:
        virtual void fn() { }
    };
    
    class C : public virtual A {
    public:
        virtual void fn() { }
    };
    
    // does not override fn!!
    class D : public B, public C {
    public:
        virtual void doit() {
            B::fn();
            C::fn();
        }
    };
    
    int main(int argc, char **argv) {
      D d;
      d.doit();
      return 0;
    }
    

    You can, however derive non-virtual from A in C and B, but then you have no diamond inheritance anymore. That is, each data-member in A appears twice in B and C because you have two A base-class sub-objects in an D object. I would recommend you to rethink that design. Try to eliminate double-objects like that that require virtual inheritance. It often cause such kind of conflicting situations.

    A case very similar to this is when you want to override a specific function. Imagine you have a virtual function with the same name in B and C (now without a common base A). And in D you want to override each function but give different behavior to each. Depending whether you call the function with a B pointer or C pointer, you have the different behavior. Multiple Inheritance Part III by Herb Sutter describes a good way of doing that. It might help you decide on your design.

    0 讨论(0)
  • 2020-12-03 00:30

    Vividos has already answered the main part of the post. Even if I would use the scope operator instead of the more cumbersome static_cast<> + dereference operator.

    Depending on the task at hand, maybe you can change the inheritance relationship from D to B and C for a less coupling composition (plus possibly inheritance from A). This is assuming that you don't need D to be used polimorphically as either B or C, and that you don't really require B and C sharing the same base instance.

    If you opt for composition, you can receive the B and C as arguments to your constructor as references/pointers of type A, making D completely unaware of the types B and C. At that point, you can use a container to hold as many A derived objects. Your own implementation of fn() (if you so decide) or any other method.

    0 讨论(0)
  • First question, yes, B and C can define fn() as a virtual function. Second, D can of course access B::fn() and C::fn() by using the scope operator :: Third question: D must at least know B and C, since you have to define them on the inheritance list. You can use templates to let the types of B and C open:

    class A
    {
    public:
       virtual ~A() {}
       virtual void fn() = 0;
    };
    
    class B: public A
    {
    public:
       virtual ~B() {}
       virtual void fn(){ std::cout << "B::fn()" << std::endl; }
    };
    
    class C: public A
    {
    public:
       virtual ~C() {}
       virtual void fn(){ std::cout << "C::fn()" << std::endl; }
    };
    
    template <typename TypeB, typename TypeC>
    class D: public TypeB, public TypeC
    {
    public:
       void Do()
       {
          static_cast<TypeB*>(this)->fn();
          static_cast<TypeC*>(this)->fn();
       }
    };
    
    typedef D<B, C> DInst;
    
    DInst d;
    d.Do();
    

    About the wish to automatically enumerate all fn() functions of all classes that D inherits from: I'm not sure if that is possible without resorting to MPL. At least you can extend my example above with versions that deal with 3 and more template parameters, but I guess there is an upper (internal compiler-)limit of number of class template parameters.

    0 讨论(0)
提交回复
热议问题