Vector template question
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?
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:
class foo_base {
/* ... */
};
template <typename T> class foo: public foo_base {
/* ... */
};
Now, you can create a vector<foo_base*>
to store pointers to foo_base
objects, which are in turn all specializations of 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.
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.
class IFoo{
virtual void bar() = 0;
virtual int baz() = 0;
};
template<class T>
class Foo : IFoo{
// concrete implementations for bar and baz
};
// somewhere in your code:
std::vector<IFoo*> vecFoo.
vecFoo.push_back(new Foo<int>);
The obvious problem with that is, that you can't need to know each possible return value for your bar
and baz
functions.
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 of foo<?>
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 put baseclass
pointers into the vector (preferably using shared_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.
class common_base {
/* functions to access the non-templates parts of a foo<T> .. */
};
template<typename T> class foo : public common_base { };
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
template <class T>
my_vector
{
typedef std::vector<Foo<T>*> type;
}
If, instead, you can afford polymorphic interface for your Foo guy, I would do that as it was already suggested.
精彩评论