指向抽象模板基类的指针? [英] A pointer to abstract template base class?

查看:30
本文介绍了指向抽象模板基类的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚这一点.我需要一个抽象模板基类,它如下:

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

现在,我从中得出它指定了 Dendrite 的确切用法.

现在问题来了.

如何创建指向没有特定类型的基类的指针向量我想稍后通过将元素推送到它来指定?类似的东西:

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?

推荐答案

通常这是通过从接口类 IE 继承的模板来完成的:

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

然后你的 IDendrite 类可以存储为指针:

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

给你

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*);
};

这篇关于指向抽象模板基类的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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