Virtual inheritance and static inheritance - mixing in C++

前端 未结 6 667
误落风尘
误落风尘 2020-12-29 13:33

If you have something like this:

#include 

template class A
{
public:
    void func()
    {
        T::func();
    }
};

c         


        
6条回答
  •  既然无缘
    2020-12-29 14:22

    How could you implement class A such that if B has a virtual override, that it is dynamically dispatched, but statically dispatched if B doesn't?

    Somewhat contradictory, isn't it? A user of class A may know nothing about B or C. If you have a reference to an A, the only way to know if func() needs dynamic dispatch is to consult the vtable. Since A::func() is not virtual there is no entry for it and thus nowhere to put the information. Once you make it virtual you're consulting the vtable and it's dynamic dispatch.

    The only way to get direct function calls (or inlines) would be with non-virtual functions and no indirection through base class pointers.

    Edit: I think the idiom for this in Scala would be class C: public B, public A (repeating the trait with the child class) but this does not work in C++ because it makes the members of A ambiguous in C.

提交回复
热议问题