Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit template class with nested class

I want to create a class B that inherits from template class A. And I want the B's nested class E to be the template parameter in this inheritance. More visually:

template <class T>
class A {
}

class B : public A<B::E> {
    class E {
        int x;
    }
}

class C : public A<C::E> {
    class E {
        int x;
        int y;
    }
}

I think the problem is that the compiler doesn't know that the class B will have a nested class E by the time it's processing the declaration of B, since I'm getting the error:

no member named 'E' in 'B'

I've seen this similar question, but I would like to confirm that there's no direct solution to this conflict before giving up with this approach.

Thanks!

like image 956
Gonzalo Solera Avatar asked Sep 07 '25 11:09

Gonzalo Solera


1 Answers

I don't think it can be done directly.

One obvious approach would be something like defining B::E and C::E in some other namespace (to at least keep them out of the global namespace), then use them inside of the "parent" classes:

template <class T>
class A { /* ... */ };

namespace B_detail {
    class E { /* … */ };
}

class B : public A<B_detail::E> { /* ... */ };

namespace C_detail {
    class E { /* ... */ };
}

class C : public A<C_detail::E> { /* ... */ };

Depending upon the situation, there's a decent chance you'd also need/want to declare *_detail::E a friend of B/C.

like image 160
Jerry Coffin Avatar answered Sep 10 '25 10:09

Jerry Coffin