Search code examples
c++templatesparameter-pack

Initialize more than one unknown base classes


If base class is unknown to library (it is known to client), it is not so difficult to handle its constructor. The code looks like:

template<typename Parent>
struct AAAAA : public Parent
{
    using Parent::Parent;

    template<typename ...Args>
    AAAAA(int a, int b, Args ...args) : Parent(args...) {}
};

What is the best approach, if all>1 base classes are unknown?

template<typename P1, typename P2>
struct AAAAA : public P1, public P2
{
    // ...CTOR....???
};

My first thoughts are these:

  • A parameter pack "split" type.
  • 2 tuples which converted to parameter packs.

For both thoughts, I don't know this time how, and if it is possible.


Solution

  • What comes in handy here is std::make_from_tuple.

    This is how you can use a tuple for a single parent:

    #include <tuple>
    struct foo { 
        foo(int,double){}
        foo(const foo&) = delete;
        foo(foo&&) = default;     
    };
    
    template<typename Parent>
    struct A : public Parent
    {
        template<typename T>
        A(const T& args) : Parent(std::make_from_tuple<Parent>(args)) {}
    };
    
    int main() {
        A<foo> a{std::make_tuple(1,2.0)};
    }
    

    Adding a second parent should be straightforward.

    Note that Parent has to be at least move-constructible to make this work.