cheking type with iterators

Hi guys,
Assuming I have a list of pointers to a generic type T:
1
2
3
4
 
#include <vector> 
//...
list<T*> myList; 


Now assuming I want to go on the list, and if T's type is matched to the type I'm looking for, then cast it to this type and do something. List shown here:

1
2
3
4
5
6
 
	list<T*>:: const_iterator iter= myList.begin();
	for(; iter!=myList.end(); ++iter){ 
		if( typeid(*iter)==typeid(Something*)) //RUN-TIME ERROR 
			dynamic_cast<Something*>(*iter)->DoSomething(); 
	}


how do I fix this run-time error?
Thanks !
1. For pointers and other small/primitive types, use std::vector, not std::list - the performance gain is huge.
2. Make sure you have RTTI enabled.
3. Compare typeid(**iter) == typeide(Something) or use this idiom:
1
2
3
4
if(Something &s = dynamic_cast<Something &>(**iter))
{
    s.DoSomething();
}
4. If you need to check the type of an object and cast like this, you have a design flaw.
Last edited on
Topic archived. No new replies allowed.