views:

253

answers:

2

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
{
    int 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;
}
+3  A: 

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.

Ponting
See type TypeToThreadIterMapStorage, want to do the assignment in the container for this type.
lsalamon
+2  A: 

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);
Martin York
Bank shot. Accepted solution.
lsalamon
Was too busy thinking about which cast to use..didn't see this one until it was too late :-(
Ponting