Typcasting vector<object> in C++?
I have two classes, obs开发者_C百科tacle and boid, boid inherits from obstacle.
Now I want to write some functions that can work with objects of both classes, so that passing vector<boid>
does work as well as vector<obstacle>
.
When I typecast like this and try to access the size of the vector I get a number of 1840700394 instead of 60:
vector<boid>* boids; ....
cout << ((vector<obstacle>*)boids)->size() << endl;
I also tryed "reinterpret_cast" but same problem.
C++ templates are not like C# and Java generics. A template instantiation is a complete class, and is not related to other template instantiations in any way whatsoever. One cannot cast between them.
(Side Note: If you were using static_cast
instead it would have caught this for you....)
You can't cast a vector to a different type of vector like that. If you need a generic function that works with both types of objects, you can use a function template.
template <typename T>
void func(const std::vector<T>& vec)
{
....
}
This function will accept a vector containing any type of object.
Also, see Roger Pate's comment below. You can let the function accept any type of container (or any object that implements the appropriate semantics) by just saying:
template <typename T>
void func(const T& container) { ... }
A simple way to solve this kind of problem is to use a std::vector<obstacle *>
. Then you can populate your vector with pointers to any object that inherits from obstacle.
精彩评论