简体   繁体   中英

Templated class unknown type over multiple layers

I've got following class Foo and 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. 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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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