Julien Lopez
Julien Lopez

Reputation: 1021

variadic template complex inheritance generation

Playing a bit with variadic templates to try and see what could be done with them, I found myself wondering about something:

Let's suppose I have a class which can take several other classes as template parameters, each of them have a nested class (let's call it nested_class):

template<typename... Classes> class MyClass {
    class InnerClass { ... };
};

what I would like to achieve is inside MyClass, create a class that inherits from each of the parameters classes nested class.

For example:

class A1 {
public:
    struct nested_class {
        do_stuff() { ... }
    };
};
class A2 {
public:
    struct nested_class {
        do_other_stuff() { ... }
    };
};

using C = MyClass<A1, A2>;

the idea would be that C has it's nested class InnerClass that inherits A1::nested_class and A2::nested_class.

Would there be anything that could achieve such a thing? I personally can't figure out a way, but maybe it is possible. Would inheritance hierarchy builders like Alexandrescu's Hierarchy Generators (which can be found in Loki: http://loki-lib.sourceforge.net/html/a00653.html) would be of any help?

thanks in advance if anyone has an idea.

Upvotes: 3

Views: 721

Answers (1)

awesoon
awesoon

Reputation: 33661

To make InnerClass derived from all nested_classes, you should use Classes::nested_class... pattern:

#include <iostream>
#include <type_traits>

template <class... Classes>
class Myclass
{
public:
    class InnerClass: public Classes::nested_class...
    {

    };
};

class A1 {
public:
    struct nested_class {
        void do_stuff() { /*...*/ }
    };
};
class A2 {
public:
    struct nested_class {
        void do_other_stuff() { /*...*/ }
    };
};

int main()
{
    using Class = Myclass<A1, A2>;

    std::cout << std::is_base_of<A1::nested_class, Class::InnerClass>::value << std::endl;
    std::cout << std::is_base_of<A2::nested_class, Class::InnerClass>::value << std::endl;

    return 0;
}

Upvotes: 6

Related Questions