I’m currently writing WinRT code, but I imagine this question applies to all C++. Upon user interaction, the framework calls one of my functions passing in a vector with generic Object^ pointers (very similar to void* for you non-WinRT folks). I already know what type of objects are in the vector and I’d like to cast the vector to that object type.
Example:
MyClass::SomeFunction(Vector<Object^>^ myList) {
// Warning: The following line doesn't work!!
Vector<SpecificType^>^ myTypedList = static_cast<Vector<SpecificType^>^>(myList);
// Here, I go on to interact with the templated vector.
...
}
The compiler doesn’t allow me to use static_cast. safe_cast throws an exception. dynamic_cast doesn’t throw an exception, but returns a null pointer.
Is there a way I can cast this thing, or do I literally have to create a new vector and copy all the members over (casting each from Object^ to SpecificType^ on insertion)?
You cannot cast
Vector<Object^>to any otherVector<>because there is no inheritance involved between them. The only thing that you can do is cast each element into the right class. So, if you want aVector<SpecificType^>you do indeed need to create it anew. Not that it is too hard: