3

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.

1 Answer 1

6

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.