Inheriting a template class using a type defined in a derived class

I am trying to inherit from a template class using the type defined in the derived class. I tried this, but it does not work.

class A : std::vector<A::B> { enum B { foo, bar }; }; 

Is there an elegant way to do this?

Edit: I know that it works if B is defined previously. But I'm looking for a solution that allows you to encapsulate type B inside class A.

+1
c ++ inheritance templates
source share
4 answers

In my opinion, the best (admittedly, indirect) solution is to use composition rather than inheritance:

 class A { enum B { foo, bar }; std::vector<B> bs; }; 

If for some reason you need (or really want to) use private inheritance to insert a vector into your object, then the type must be defined before the class in the namespace scope, since types cannot be used before they are declared. If they are not accessible to users of the class, and you do not want to pollute the namespace containing your class, then you can put them in the namespace to indicate that they are implementation details:

 namespace details { enum B { foo, bar }; } class A : std::vector<details::B> { typedef details::BB; // if you don't want to write "details::B" everywhere static const B foo = details::foo; // if you don't want to write "details::foo" everywhere // and so on. }; 
+1
source share

You cannot forward an enum declaration in C ++ 03. Just use the regular composition, having the vector as a member and forwarding manually.

+3
source share

You will need to define enum B before using for inheritance.

In addition, you do not inherit from the standard vector , right?

+2
source share

Thanks to everyone for your answers, but I found a solution (edit: bad):

 namespace { enum B_type { foo, bar }; } class A : std::vector<B_type> { typedef value_type B; }; 
0
source share

All Articles