【问题标题】:A pointer to abstract template base class?指向抽象模板基类的指针?
【发布时间】:2010-12-02 14:58:43
【问题描述】:

我想不通。我需要一个抽象模板基类,它 如下:


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

        virtual ~Dendrite()
        {
        }

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

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

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

现在是问题。

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


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

这是可能的还是我在这里遗漏了一些非常基本的东西?

【问题讨论】:

标签: c++ inheritance templates polymorphism abstract


【解决方案1】:

通常这是通过您的模板从接口类 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 类可以存储为指针:

std::vector<IDendrite*> m_dendriteVec;

但是,在您的情况下,您将模板参数作为界面的一部分。您可能还需要包装它。

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

【讨论】:

    【解决方案2】:

    是的,这是可能的。只要确保提供虚函数和虚析构函数即可。另外,你可以使用 typeid 来获取实际的类型(也可以使用 dynamic_cast 来检查类型)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 2015-12-28
      相关资源
      最近更新 更多