我有一个抽象的基类 User
,被 Student
和 Professor
继承。 User
中有用于向文件中写入数据(序列化)的虚函数,派生类对其进行了重写。
void Student::write(std::ofstream& ofs) const {
ofs << typeid(*this).raw_name() << id << "," << get_name() << "," << get_surname() << ",";
}
void Professor::write(std::ofstream& ofs) const {
ofs << typeid(*this).raw_name() << title << "," << get_name() << "," << get_surname() << ",";
}
它还具有从文件读取(反序列化)的功能。问题是,当我从文件中读取
typeid(* this).raw_name()
时,我不知道如何访问 Student
或 Professor
,以便我可以实例化其中之一。 我正在使用模板数据结构类,所以无法明确检查。 template <typename T>
class UndirectedGraph { ...
void for_each_DFS(int vertex, const std::function<void(const T&)>& func) const {
for (const auto value : *nodes.at(vertex))
func(value);
}
void for_each_DFS(int vertex, const std::function<void(T&)>& func) {
for (auto value : *nodes[vertex])
func(value);
}
virtual void write(std::ofstream& ofs) const override {
if (std::is_pointer<T>::value)
for_each_DFS(0, [&ofs](const T& obj) { ofs << *obj; });
else
for_each_DFS(0, [&ofs](const T& obj) { ofs << obj; });
}
virtual void read(std::ifstream& ifs) override {
std::string type;
for_each_DFS(0, [&ifs](T& obj) {
// here I get that info, but how do I use it do declare type of derived class?
std::getline(ifs, type, ',');
ifs >> obj;
});
}
}
std::unique_ptr<User*> create_user(const std::string& type);
,实现是一系列的if
,然后User
实例可以完成其解析。 - MatGauto name = ReadName(...); auto metadata = Base :: GetMetadata(name); auto * obj = metadata-> createObj(); obj-> read(...);
- Osyotr