从模板类继承,使用派生类中定义的类型
我试图使用派生类中定义的类型从模板类继承。 我已经尝试过这个,但它不起作用。
class A : std::vector<A::B>
{
enum B { foo, bar };
};
有没有一种优雅的方法来做到这一点?
编辑:我知道如果 B 较早定义,它就可以工作。但我正在寻找一种允许将类型 B 封装在 A 类中的解决方案。
I'm trying 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法在 C++03 中转发声明枚举。只需使用正常的组合,将向量作为成员并手动转发即可。
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.
在使用枚举 B 进行继承之前,您必须先定义它。
另外,您不是从标准
vector
继承的,是吗?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:
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:
感谢大家的回答,但我刚刚找到了一个(编辑:坏)解决方案:
Thanks everyone for your answers, but I just found a (edit: bad) solution :