Sunday, June 8, 2014

instanceof for C++: typeid

#include <typeinfo>
bool Manager::hasTask( const type_info &taskType )
{
list<Task>::iterator it = mTasks.begin();
for (it; it != mTasks.end(); ++it )
{
Task task = (*it);
if(typeid(*task) == taskType) return true;
}
return false;
}
// usage
if (!hasTask(typeid(TrainWorkersTaskClass)))
{}
view raw typeid.cpp hosted with ❤ by GitHub
Always be certain that pointers are dereferenced when using typeid. It can be a common error, and the compiler won't give any warning.

No comments:

Post a Comment