从模板类继承,使用在派生类中定义的类型 [英] Inheriting from a template class, using a type defined in the derived class

查看:76
本文介绍了从模板类继承,使用在派生类中定义的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图继承一个模板类,使用在派生类中定义的类型。

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 ?

编辑:我知道如果B之前定义它的工作。但我正在寻找一个解决方案,允许封装在A类内的类型B.

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.

推荐答案

在我看来, (可以肯定是间接的)解决方案是使用组合而不是继承:

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.
};

这篇关于从模板类继承,使用在派生类中定义的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆