gpt4 book ai didi

c++ - 指向抽象模板基类的指针?

转载 作者:可可西里 更新时间:2023-11-01 15:51:43 26 4
gpt4 key购买 nike

我想不通。我需要一个抽象模板基类,它是以下内容:


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

virtual ~Dendrite()
{
}

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

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

现在,我从中得出 Dendrite 的具体用法。

现在是问题。

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


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

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

最佳答案

通常这是由您的模板继承自接口(interface)类 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*);
};

关于c++ - 指向抽象模板基类的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1497552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com