0

I'm not entirely sure if this is possible or what syntax I would need to employ if it is, but I want to make a class that publicly derives from all of the classes provided in the variadic arguments so that I could derive from that single class and thereby derive from all the classes that were supplied to it.

What I am wanting to be able do is declare something like:

class MyClass : public InheritFrom<ClassA, ClassB,  ,,,> {
};

So that the InheritFrom template class effectively publicly derives from all of the classes listed. In my use case, each class provided will have a default constructor, so no special constructors will have to be called.

What I had tried to do was this:

template <class A, class ... Args> class InheritFrom : public A, public InheritFrom<Args...> {
...
};

template <class A> class InheritFrom : public A {
...
};

And effectively turn what would otherwise have been a multiple inheritance into a single inheritance heirarchy, but the compiler complains about the second InheritFrom declaration, which was supposed to be a specialization where only one class is given, as being a redeclaration with one parameter. There will ultimately be much more detail within the body of each of these classes, but for now I'm just trying to figure out how to get the syntax right.

0

1 Answer 1

3

In c++17 you just need to expand the pack, nothing more to it.

#include<iostream>
#include<type_traits>

template <class ...T> class InheritFrom : public T... {
};

struct Foo {};

struct Bar {};

struct Baz : InheritFrom<Foo, Bar> {};

int main(){
    std::cout << std::is_base_of_v<Foo, Baz> << std::is_base_of_v<Bar, Baz>;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Apologies, I realize I'd didn't make this clear in my question (because I didn't know it was relevant), but InheritFrom needs to have the name of the first class in the list of classes passed to it. Without explicitly naming it as its own argument, is there any way to extract it from the variadic arguments?
@markt1964 Not sure exactly what Without explicitly naming it as its own argument means. You can do template <class First, class ...Rest> class InheritFrom : public First, public Rest... to get the name of the first one.
Or maybe you're looking for a recursive approach like the one you attempted so you can do something with each base class? If so, what is that extra thing?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.