Here is a code:
class Base {
public:
long index;
};
class Derived : public Base {
public:
bool value;
};
void call(map<char *, Base *> *base) {
map<char *, Base *>::iterator it = base->begin();
cout << it->second->index << endl;
}
void test(void) {
map<char *, Derived *> *d = new map<char *, Derived *>;
call(d);
}
Compiler alerts an error:
error C2664: 'call' : cannot convert parameter 1 from 'std::map<_Kty,_Ty> *' to 'std::map<_Kty,_Ty> *'
1> with
1> [
1> _Kty=char *,
1> _Ty=Derived *
1> ]
1> and
1> [
1> _Kty=char *,
1> _Ty=Base *
1> ]
1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
I understand why this error is happened. I do not understand how to make it work. What kind of cast and how to use it?
UPD
I'm sorry for imprecision, let me explain more details. I have two sets of data represented by ClassA and ClassB. Both of these classes have one common member - an "index", for example. Both sets are wrapped into a maps (special thanks to Rob for a significant correction with char*):
std::map<char, ClassA>
std::map<char, ClassB>
Sometime I need to iterate over both maps to get a value of a common member "index". I'm trying to avoid code duplication and make just one function to iterate over both maps.
I thought I may extract a superclass with a common member and make a function with parameter like this one:
std::map<char, SuperClassAB>
or
std::map<char, SuperClassAB>::iterator
But looks like it's a bad idea.
UPD2
One smart guy gave me the solution:
template <class T>
void call(map<char, T> *base) {
map<char, T>::iterator it = base->begin();
cout << it->second->index << endl;
}
void test(void) {
map<char, Derived *> d;
call(&d);
}
map<char*, Derived*>is unrelated to amap<char*, Base*>, and rightly so. Otherwise, you could have the same problems as withBase**andDerived**.map<char*, Derived*> d;. It's also error-prone to use owning raw pointers inside Standard Library containers.)