I'm t开发者_如何学JAVArying to inherit from a template class, using a type defined in the derived class. I have tried this, but it doesn't work.
class A : std::vector<A::B>
{
enum B { foo, bar };
};
Is there an elegant way of doing this ?
Edit : I know that it works if B is defined earlier. But i'm looking for a solution that allows encapsulating the type B inside the A class.
You can't forward declare an enum in C++03. Just use normal composition by having a the vector as a member and forwarding by hand.
You will have to define enum B
before it's use to inherit.
Also, you're not inheriting from the Standard vector
, are you?
In my view, 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 embed the vector in your object, then the type will need to be defined before the class, at namespace scope, since types cannot be used before they are declared. If they are not indended to be accessed by users of the class, and you don't want to pollute the namespace containing your class, then you could put them inside a namespace to indicate that they are implementation details:
namespace details
{
enum B { foo, bar };
}
class A : std::vector<details::B>
{
typedef details::B B; // 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.
};
Thanks everyone for your answers, but I just found a (edit: bad) solution :
namespace
{
enum B_type { foo, bar };
}
class A : std::vector<B_type>
{
typedef value_type B;
};
精彩评论