how to solve this problem with a cast of iterator?
The compiler (VC8) error is:
error C2680: 'std::_Tree<_Traits>::iterator' : invalid target type for dynamic_cast the source code to simulate the error : [EDIT]source fixed now#include <map>
#include <string>
struct tag_data
{
in开发者_运维知识库t in;
int on;
std::string sn;
};
class myclass
{
private:
typedef std::map<std::string, tag_data> TypeData;
TypeData MapStorage;
typedef std::map<unsigned long, TypeData::iterator > TypeToThreadIterMapStorage;
TypeToThreadIterMapStorage ThreadIterMapStorage;
public:
bool find( std::string& k)
{
TypeData::const_iterator theData ;
theData = MapStorage.find(k);
//ThreadIterMapStorage [ 0 ] = MapStorage.begin();// this is ok
ThreadIterMapStorage [ 1 ] = dynamic_cast<TypeData::iterator>(theData); // the error occurs here
return theData != MapStorage.end();
}
virtual ~myclass(){}
};
int _tmain(int argc, _TCHAR* argv[])
{
myclass mc;
return 0;
}
First of all your dynamic_cast syntax is wrong (or may be formatting issue?):
dynamic_cast syntax: dynamic_cast<DerivedClassName*>(BaseClass*)
OR
dynamic_cast<DerivedClassNameReference>(BaseClassReference)
This code looks very suspcious to me. What are you trying to achieve? Why do you want to dynamic_cast an iterator? That doesn't make any sense.
EDIT
map's begin()
has two overloads, one which returns the const_iterator and the other which returns a non const_iterator. In your commented code, since your TypeToThreadIterMapStorage
map's value_type is a non-const iterator the second version of begin() is used. However, the type of theData iteartor is a const_iterator and the compiler is complaining that const_iterator can not be converted into a non-const iterator. What you require is a const_cast
to remove the constness of the object and not dynamic_cast
. But note that this is a dangerous thing to do.
The simpler way is to declare theData as a non-const iterator.
What makes you think that TypeData::iterator and TypeData::const_iterator are even related?
Why not change the type of 'theData' to an iterator?
TypeData::iterator theData = MapStorage.find(k);
精彩评论