Getting a list of a class's nested classes at compile time

Viewed 54

I want to get a list, so to speak, of the nested classes of some class, which can then be used as input to the parameter pack for another class.

For example, here is the class that would contain the nested types:

class Foo
{
public:
    class FirstNested
    {
        // ...
    }

    class SecondNested
    {
        // ...
    }

}

and here is the class with the parameter pack that would use the nested types:

template <class...Ts>
class UsesFooNestedTypes
{
private:
    std::variant<Ts...> _variantOfFooNestedTypes;  // irrelevant, just an exmaple of what might be done with the types.
}

is there any way to do this, or something similar?

UsesFooNestedTypes<get_nested_types_of<Foo>> fooNestedTypesUser;

Edit: Upon giving it some thought, I’ve realised that this question doesn’t reflect my actual problem closely enough. So, I have created a more specific question here: Automatically get nested state classes to use in std::variant variadic parameter for state pattern

1 Answers

Directly getting the types of all nested classes of a specific class requires the support of reflection, which is currently impossible in C++.

If you can modify Foo, then you can define a member type and use a tuple to store all nested classes of Foo

class Foo {
 public:
  class FirstNested { };
  class SecondNested { };
  // ...
  using NestedClasses = std::tuple<FirstNested, SecondNested, ...>;
};

Then use some meta-programming tricks to get the types of these nested classes and instantiate std::variant

template <class Tuple>
class UsesFooNestedTypes;

template <class... Ts>
class UsesFooNestedTypes<std::tuple<Ts...>> {
 private:
  std::variant<Ts...> _variantOfFooNestedTypes;
};

int main() {
  UsesFooNestedTypes<Foo::NestedClasses> fooNestedTypesUser;
}
Related