矢量模板问题
问题是因为我对向量和模板没有做太多工作。
如果我有一个模板类 foo 类,并且我想创建一个 foo 指针向量,无论 foo 类型如何,语法会是什么样子?
Question as I have not done much with vectors and templates.
If I have a class foo that is templated class and I want to create a vector of foo pointers regardless of foo type, what would the syntax look like?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
没有直接的方法可以做到这一点。同一模板的不同实例被视为彼此无关的不同类。
如果您想统一对待它们,一种选择是创建一个基类,模板
foo
类将从该基类继承。例如:现在,您可以创建一个
vector
来存储指向foo_base
对象的指针,这些对象又是foo
的所有特化>。There is no direct way to do this. Different instantiations of the same template are treated as distinct classes with no relation to one another.
If you want to treat them uniformly, one option is to create a base class that the template
foo
class then inherits from. For example:Now, you can create a
vector<foo_base*>
to store pointers tofoo_base
objects, which are in turn all specializations offoo
.你不会。类模板
foo
的每个实例(例如foo
、foo
等)都是一个独特类型。foo
本身不是类型。您需要为它们提供一些基类并存储指针,利用多态性。
You wouldn't. Every instantiation of the class template
foo
(e.g.foo<int>
,foo<char>
etc) is a distinct type.foo
itself is not a type.You'd need some base class for them and store pointers, making use of polymorphism.
不可能。当您在任何地方使用类模板时,您需要在类型上实例化它。
避免这种情况的一种可能性是为 foo 提供一个多态接口基类并拥有这些指针的向量。
明显的问题是,您不需要知道
bar
和baz
函数的每个可能的返回值。Not possible. When you use a class template anywhere, you need it instantiated on a type.
One possibility to circumvent that, is to provide a polymorphic interface base class for
foo
and have a vector of those pointers.The obvious problem with that is, that you can't need to know each possible return value for your
bar
andbaz
functions.您不能拥有
foo
向量。编译器在创建向量时需要准确地知道它存储的类型,因为foo
的每个实例化都可能具有不同的大小和完全不同的成员(因为您可以提供显式和部分特化) )。您需要为 foo提供一个公共基类,然后将
baseclass
指针放入向量中(最好使用shared_ptr
或类似的东西) 。作为替代方案,有一些现成的类可以向您隐藏这一点,并充当引用的容器。其中有
boost::ptr_vector
,但它也需要一个通用类型来存储。You cannot have a vector of
foo<?>
. The compiler when it creates the vector needs to know precisely what type it stores because every instantiation offoo<?>
could potentially have a different size and entirely different members (because you can provide explicit and partial specializations).You need to give the
foo<T>
a common base class and then putbaseclass
pointers into the vector (preferably usingshared_ptr
or something similar).As an alternative there are ready classes that hide this from you and act like a container of references. Among them is
boost::ptr_vector
, which however also need a common type to store.如果您尝试模拟概念:“指向 Foo 的指针向量”而不指定 T,则您正在尝试模拟当前标准不支持的模板 typedef。
解决方法是
,相反,如果您可以为您的 Foo 人员提供多态接口,我会按照已经建议的那样这样做。
If you are trying to emulate concept: "vector of pointers to Foo" without specifying T, you are trying to emulate template typedefs that are not supported by current standard.
The workaround is
If, instead, you can afford polymorphic interface for your Foo guy, I would do that as it was already suggested.