1

Let's say that I have the following very simple CRTP base class:

template< class D, class T >
struct Base
{

    T foo() 
    {   
        return static_cast< D* >(this)->foo_i();
    }

};

And also, a handful of deriving classes. Everything works well, but there is a problem: there's one particular situation (or perhaps a couple) where I would really, really like two of the classes to have runtime polymorphic behaviour (need to put them in containers). In other words, I'd like some of the deriving CRTP classes to have virtual versions as well. So, I came up with the following class:

template< class T >
struct VirtualBase : public Base< VirtualBase< T >, T >
{

    virtual T foo_i() = 0;

};

Now, where I need runtime polymorphism, I just derive from this class. Let's say that I want my derived class DerivedB to have a virtual version. The vanilla DerivedB looks like this:

template< class T >
struct DerivedB : public Base< DerivedB< T >, T >
{

    T foo_i() 
    { 
        std::cout << "I'm special!\n";
        return T(); 
    }

};

What I would like to do is essentially to add an extra template parameter to this class so that I can at compile-time select whether I derive from Base (if I want simulated 'dynamic' binding) or VirtualBase (if I want real dynamic binding). Something like the following pseudo-C++:

template< class B, class T >
struct DerivedB : public B< DerivedB< T >, T >
{

    T foo_i() 
    { 
        std::cout << "I'm special!\n";
        return T(); 
    }

};

So for plain CRTP, pass Base as B and for a virtual class, pass VirtualBase as B. The problem, of course, is that they take a different number of arguments (Base needs the type of the deriving class), and I cannot come up with a working solution.

So, how would I select the base class at compile-time? Or, if this too complicated/impossible, what would be the easiest way to have static (CRTP) and dynamic (virtual) versions of a class, where otherwise the implementation is identical?

1 Answer 1

2

The simplest way is probably just to add "class D" as a unused template parameter of VirtualBase, so that it conforms to the same interface.

If you can't change VirtualBase, you could use a intermediate template:

template <class D, class T> class VirtualBaseWrapper : public VirtualBase<T>{}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.