[英]How to deserialize polymorphic classes?
我有抽象基礎 class 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() << ",";
}
它還具有用於從文件讀取(反序列化)的 function。 問題是,當我從文件中讀取typeid(*this).raw_name()
時,我不知道如何訪問Student
或Professor
,因此我可以實例化其中一個。 我正在使用模板數據結構 class,所以我無法明確檢查。
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::any
和std::type_index
的可能解決方案。
#include <any>
#include <string>
#include <typeinfo>
#include <typeindex>
#include <unordered_map>
class A {};
class B {};
template<typename T>
std::string write(){
static const std::unordered_map<std::type_index, std::string> kTypeNames{{typeid(A), "A"}, {typeid(B), "B"}};
return kTypeNames.at(typeid(T));
}
std::any read(const std::string& s){
if(s == "A") return A{};
if(s == "B") return B{};
return {};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.