c++templatesc++11inheritancevariadic-templates

Variadic templates and multiple inheritance in c++11


i'm trying to achieve something like this:

I have a templated base class which i want to inherit dynamically

template<typename A, typename B>
class fooBase
{
public:
    fooBase(){};
    ~fooBase(){};
};

desired method: (something like this, not really sure how to do it)

template <typename... Interfaces>
class foo : public Interfaces...
{
public:
    foo();
    ~foo();
}

and my goal is to have the foo class act like this:

second method:

class foo()
    : public fooBase<uint8_t, float>
    , public fooBase<uint16_t, bool>
    , public fooBase<uint32_t, int>
    // and the list could go on
{
    foo();
    ~foo();
}

with the second method the problem is that if i instantiate an foo object, it will inherit all the time those 3 base classes, i want to make it more generally and when instantiate a foo object, give it with variadic templates the parameters for the base classes, so that i can use the foo class for other types(maybe will inherit just one base class, maybe five)

Thank you

example for instantiating foo

foo<<uint8_t, float>, <uint16_t, bool>, <uint32_t, int>, /* and the list could go on and on */> instance

Solution

  • You could try recursive variadic templates, taking 2 arguments at a time to add a derivation from fooBase.

    It could be something like:

    template<typename A, typename B>
    class fooBase
    {
    public:
        fooBase(){};
        ~fooBase(){};
    };
    
    template<typename A, typename B, typename ... C>
    class foo: public fooBase<A, B>, public foo<C ...> {
    };
    
    // termination version by partial specialization
    template<typename A, typename B>
    class foo<A, B>: public fooBase<A, B> {
    };
    

    You can then declare:

    foo<uint8_t, float, uint16_t, bool, uint32_t, int> bar;
    

    and bar will be a subobject of fooBase<uint8_t, float>, fooBase<uint16_t, bool> and fooBase<uint32_t, int>