指向抽象模板基类的指针?
我无法弄清楚这一点。我需要有一个抽象模板基类,它 如下:
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>()).
};
这可能吗,还是我在这里遗漏了一些非常基本的东西?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,这是通过从接口类 IE 继承的模板来完成的:
然后您的 IDendrite 类可以存储为指针:
但是,在您的情况下,您将模板参数作为接口的一部分。您可能还需要将其包装起来。
给你
Typically this is done by your template inheriting from an interface class, IE:
and then you're IDendrite class could be stored as pointers:
However, in your situation, you are taking the template parameter as part of your interface. You may also need to wrap this also.
giving you
是的,这是可能的。只要确保提供虚拟函数和虚拟析构函数即可。另外,您可以使用 typeid 来获取实际类型(以及dynamic_cast来检查类型)
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)