I have the following in C++/CLI: (take note of my errors in comments)
class Base{...}
class Derived : public Base{...}
public ref class CliClass
{
public:
std::list<Base*> *myList;
CliClass()
{
myList = new list<Base*>();
}
AddToList(Derived *derived)
{
myList->push_back(derived);
}
DoCast()
{
Derived *d = nullptr;
int n = (int)myList->size();
for(int i = 0; i < n; i++)
{
//this following does not compile
//error C2440: 'type cast' : cannot convert from 'std::list<_Ty>' to 'Derived *'
d = (Derived*)myList[i];
//I've also tried this -which does not compile
//error C2682: cannot use 'dynamic_cast' to convert from 'std::list<_Ty>' to 'Derived *'
d = dynamic_cast<Derived*>(myList[i]);
}
}
}
I would like to cast myList[i] to the Derived type.. but it won’t allow me.
Any suggestions on how to cast this properly? (compile and is run-time safe – i.e. won’t blow up if wrong type)
You got it all wrong. Assuming that you have several typos in your code and mean
std::list, you are currently saying:The last line treats
myListas an array of lists, which you never created! The way to access list elements is by iteration.Here is a skeleton rewrite, hopefully you’ll be able to extract the fixes from that: