0

I have a templated struct that store's the template parameter as a nested alias like so:

template<class CHILD_TYPE>
struct ParentType {
    using ChildType = CHILD_TYPE;
};

If I know the exact type, I can access that aliased type like so:

void func() {
    ParentType<int>::ChildType var{};
    std::cout << var << std::endl;
}

What I'm trying to do is template the above function so the exact parent type is unknown, but still access the aliased type like so:

template<class PARENT_TYPE>
void func() {
    class PARENT_TYPE::ChildType var{};
    std::cout << var << std::endl;
}

This however gives me a compiler error:

error: type alias 'ChildType' cannot be referenced with a class specifier

Now I can understand that I would get a compiler error if I templated that func with something that didn't have the ChildType nested alias, but why can't I define the function like this in the first place? And is there some way (either similar to this or otherwise) to allow myself to acquire the template parameter from a generic type?

Iron Attorney
  • 1,003
  • 1
  • 9
  • 22
  • 1
    `class PARENT_TYPE::ChildType var{};` -> `typename PARENT_TYPE::ChildType var{};`. This is why I prefer to just always use `typename` and only use `class` when defining a class. – NathanOliver Sep 15 '22 at 14:18
  • Wow, that's a real gotcha nuonce. Thanks very much! I guess this is because `class` in this context means "define a class", not the same as what it means in the template context. – Iron Attorney Sep 15 '22 at 14:22
  • 1
    Yep, outside a template list `class` is not synonymous with `typename` – NathanOliver Sep 15 '22 at 14:28

0 Answers0