A pointer to abstract template base class?

这一生的挚爱 提交于 2019-12-20 12:35:32

问题


I cannot figure this out. I need to have an abstract template base class, which is the following:


template <class T> class Dendrite
{
    public:
        Dendrite()
        {
        }

        virtual ~Dendrite()
        {
        }

        virtual void Get(std::vector<T> &o) = 0;

    protected:
        std::vector<T> _data;
};

Now, I derive from this which specifies exact usage of Dendrite.

Now the problem.

How do I create a vector of pointers to the base-class with no specific type, which I want to specify by pushing elements to it later? Something like:


class Foo
{
    public:
        ...

    private:
        std::vector<Dendrite *> _inputs; //!< Unfortunately, this doesn't work...

        //! Now I could later on push elements to this vector like
        //!
        //! _inputs.push_back(new DeriveFromDendrite<double>()) and
        //! _inputs.push_back(new DeriveFromDendrite<int>()).
};

Is this possible or am I missing something very basic here?


回答1:


Typically this is done by your template inheriting from an interface class, IE:

template <class T> class Dendrite : public IDendrite
{
        public:
                Dendrite()
                {
                }

                virtual ~Dendrite()
                {
                }

                void Get(std::vector<T> &o) = 0;

        protected:
                std::vector<T> _data;
};

and then you're IDendrite class could be stored as pointers:

std::vector<IDendrite*> m_dendriteVec;

However, in your situation, you are taking the template parameter as part of your interface. You may also need to wrap this also.

class IVectorParam
{
}

template <class T>
class CVectorParam : public IVectorParam
{
    std::vector<T> m_vect;
}

giving you

class IDendrite
{
   ...
public:
   virtual ~IDendrite()
   virtual void Get(IVectorParam*) = 0; 
}

template <class T> class Dendrite : public IDendrite
{
  ...
  // my get has to downcast to o CVectorParam<T>
  virtual void Get(IVectorParam*);
};



回答2:


Yes it is possible. Just make sure to provide virtual functions, and virtual destructor. In addition, you can use typeid to get the actual type (as well as dynamic_cast to check the type)



来源:https://stackoverflow.com/questions/1497552/a-pointer-to-abstract-template-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!