c++ - 从 iostream 读取超类的子类实例。>> 运算符如何知道哪个子类?
问题描述
我有一个包含多个子类的超类元素,我们称它们为 A 和 B。我想重载 << 和 >>,以便保存和加载我的对象。
class Element
{
public:
Element();
int superProperty;
virtual void write(iostream &out)
{
out << superProperty;
}
virtual void read(iostream &in)
{
in >> superProperty;
}
};
iostream operator<<(iostream &out, const Element &elt)
{
elt.write(out);
return(out);
}
iostream operator>>(iostream &in Element &elt)
{
elt.read(in);
return(in);
}
class A : public Element
{
public:
A();
int subProperty;
void write(iostream &out)
{
Element::write(out);
out << subProperty;
}
void read(iostream &in)
{
Element::read(in);
in >> subProperty;
}
};
class B : public Element
{
public:
B();
double subProperty;
void write(iostream &out)
{
Element::write(out);
out << subProperty;
}
void read(iostream &in)
{
Element::read(in);
in >> subProperty;
}
};
使用这些定义,我可以轻松地写出我的元素文件,将每个元素写为
iostream mystream;
Element e;
...
mystream << e;
我被困的地方是把它们读回来。我希望它看起来像这样:
iostream mystream;
Element *pe;
...
pe = new Element(); // the problem is right here
mystream >> *pe;
但这行不通,因为我不知道我要读取的元素是元素还是 A 或 B。(在我的应用程序中,我从未实际实例化元素。所有对象都是子类之一.) 我求助于写出一个字符来表示班级......
if (dynamic_cast<A>(e))
{
out << 'A';
out << e;
} else if (dynamic_cast<B>(e))
{
out << 'B';
out << e;
}
然后切换/套管读取如下:
char t;
Element *pe;
...
in >> t;
switch (t)
{
case 'A':
pe = new A;
break;
case 'B':
pe = new B;
break;
}
in >> *pe;
但它似乎不优雅。
流式传输不同对象的更好方法是什么?
解决方案
本质上,这就是任何序列化解决方案都会归结为的内容。虽然优雅可能会有所提高,但使用代码生成可能仍然更好(序列化框架可以做到这一点)。
使用虚函数或映射(type_index to tag 1 )绝对可以避免动态转换。开关也可以用地图(标签到工厂)替换。甚至可以(通过一些模板魔术)使用相同的代码来初始化两个映射,例如:
using Factory = void(*)();
struct SerializationInfo {
char key;
type_index type;
Factory factory;
};
template <class T>
SerializationInfo Serializable(char key) // note that SerializationInfo is not a template!
{
return {key, typeid(T), []() { return new T(); }}; // IIRC captureless lambda is convertible to a function pointer
}
Maps buildSerializationMaps(initializer_list<SerializationInfo>);
buildSerializationMaps({
Serializable<A>('A'),
Serializable<B>('B'),
});
其中Serializable
是一个函数模板,它将所有序列化信息(键、类型 id 和工厂函数)包装在标准接口中。
推荐阅读
- patch - 如何在 Jersey Invocation Builder 中使用 PATCH 方法?
- javascript - 创建一个从原生元素派生的元素——继承?作品?
- c# - 在 netcoreapp3.0 控制台应用程序中,默认生成 myprogram.exe(扩展名为 exe)。它是什么?
- xml - 如何在 VB.Net 的 xml 文件中创建多个条目?
- c# - 如何通过循环一次清除所有组合框?
- serial-port - 使用带有 Arduino Uno 的伺服系统的串行监视器的奇怪问题
- python - 用户无权担任 IAM 角色
- vue.js - 尝试将翻译键值的 json 从 laravel 刀片传递到 vue.js 时出现问题
- javascript - 如何在反应中过滤和显示数组
- javascript - 如何在排序时将变量传递给 PHP?