在std :: map中继承基类作为值 [英] Inheritance in std::map with base class as value
问题描述
这是一个代码:
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);
}
编译器提醒一个错误:
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
对不精确的抱歉,让我解释一下更多的细节。
我有两组由ClassA和ClassB表示的数据。
这两个类都有一个共同的成员 - 例如索引。
两套都包装成一个地图(特别感谢Rob对char *进行了重大修正):
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>
有时候,我需要迭代两个地图才能获得一个普通成员index的值。
我试图避免代码重复,并且只需要一个函数来迭代这两个地图。
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>
或
std::map<char, SuperClassAB>::iterator
但是看起来像是
UPD2
一个聪明的人给了我解决方案: / p>
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);
}
推荐答案
没有人似乎建议但是您也可以使调用
一个函数模板。
No one seemed to suggest this yet, but you could also make call
a function template.
template <class Type>
void call(const std::map<char*,Type*> & base)
{
static_assert(std::is_base_of<Base, Type>::value,
"Function is only callable with maps "
"whose mapped_type is derived from Base");
/* More stuff */
}
使用 Base
,派生
以及从 Base
派生的任何其他内容。
This way the function is callable with Base
, Derived
and anything else that derives from Base
.
这篇关于在std :: map中继承基类作为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!