Search code examples
c++templatesinheritancecrtpstatic-polymorphism

curiously recurring template pattern and virtual inheritance


I am using the curiously recurring template pattern to model static polymorphism.

This works absolutely fine, until one introduces virtual inheritance (to address a diamond problem).

Then the compiler (Visual Studio 2013) starts complaining about

error C2635: cannot convert a 'Base*' to a 'Derived*'; conversion from a virtual base class is implied

Basically, this conversion is not allowed.

Why is that? Both static_cast and c-style cast fail.

Is there a solution to this that doesn't involve giving up one or the other?

EDIT:

Here a sample (remove the virtual and it works):

template <class Derived> 
struct Base
{
    void interface()
    {
        static_cast<Derived*>(this)->implementation();
    }
};

struct Derived : virtual Base<Derived>
{
    void implementation() { std::cout << "hello"; }
};

int main()
{
    Derived d;
    d.interface();
}

Solution

  • From what I found out, these can't be combined.

    The point of the curiously recurring template pattern is to resolve the call at compile time.

    As pointed out by T.C. in the comments, virtual inheritance can't be resolved until run-time.

    Which means the two don't mix, and one has to give.