简体   繁体   English

多层的模板类未知类型

[英]Templated class unknown type over multiple layers

I've got following class Foo and FooBase: 我有以下Foo和FooBase类:

class FooBase
{
public:
    virtual void A() = 0;
};

template <class T>
class Foo : public FooBase
{
public:
    virtual void A() {}
private:
    T mT;
};

FooBase is here to have a instance without needing to know the type, so I can do s.th. FooBase在这里有一个实例,不需要知道类型,所以我可以做某事。 like this: 像这样:

FooBase *foo = new Foo<int>();

Pretty standard. 很标准。 Now the issue: I want to bring the same thing to the next level. 现在的问题是:我想将同一件事带入一个新的高度。

So I've got the class: 所以我上了课:

template <class T>
class Bar : public Foo<T>
{
public:
    virtual void B() {}
};

And can of course use: 当然可以使用:

Bar<int> *bar = new Bar<int>();

Except I don't know the type of the template class. 除了我不知道模板类的类型。 So initial idea was to do the following: 因此,最初的想法是执行以下操作:

class BarBase : public FooBase
{
public:
    virtual void B() {}
};

template <class T>
class Bar : public BarBase, Foo<T>
{
};

So I can do the following: 因此,我可以执行以下操作:

BarBase *bar = new Bar<int>();

For obvious reasons this doesn't work - the question is now: How to get s.th. 由于明显的原因,这是行不通的-现在的问题是:如何获得某事。 like this to work? 像这样工作吗?

You can solve this issue with virtual inheritance . 您可以使用虚拟继承解决此问题。 This feature assures that there is only one instance of your virtually-inherited base class when you instantiate a subclass. 此功能可确保在实例化子类时,虚拟继承的基类只有一个实例。 For your example, this would look like: 以您的示例为例:

class FooBase
{
public:
    virtual void A() = 0;
};

template <class T>
class Foo : public virtual FooBase
//                   ^^
{
public:
    virtual void A() {}
private:
    T mT;
};

class BarBase : public virtual FooBase
//                      ^^
{
public:
    virtual void B() {}
};

template <class T>
class Bar : public BarBase, Foo<T>
{
};

Now you can happily create instances like you wanted: 现在,您可以愉快地创建所需的实例:

BarBase *bar = new Bar<int>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM