2017-07-22 25 views
-1

我有一個免費的模板功能,從文本文件加載:傳球*這模板函數的boost ::序列化代碼,使錯誤

// free template function 
template<class U> 
bool Main_Load(U& dataset, const std::string path) { 
    // Create an input archive 
    std::ifstream ifs(path); 
    boost::archive::text_iarchive archive_text(ifs); 

    // Load data 
    archive_text & dataset; 
} 
... 
// in main() 
Dataset1 dataset_restored; 
Main_Load(dataset_restored, filename); // <--- OK 

但我得到一個錯誤「是什麼():輸入流錯誤「當我從成員函數調用此模板函數時:

class Dataset1 { 
... 
virtual auto LoadDataset(AUX::DATA::SerializationType serialisation_type=AUX::DATA::SerializationType::Xml) -> bool { 
    Main_Load(*this, GetPath()); // <--- ERROR 
}; 
}; 
... 
// in main() 
Dataset1 dataset_restored; 
dataset_restored.LoadDataset(AUX::DATA::SerializationType::Text); 

爲什麼我可以傳遞dataset_restored而不是*這個同一個對象?我想,有什麼不妥*這個結合:

archive_text & dataset; 

編輯 我已經回答了我的問題。見下文。

+0

提供一個[MCVE]請再現問題。 – user0042

回答

1

,我發現我的代碼中的bug。

的錯誤是我的代碼488線(見下面的鏈接):

// Load/Save 
virtual auto LoadDataset(AUX::DATA::SerializationType serialisation_type=AUX::DATA::SerializationType::Xml) -> bool { 
    return AUX::DATA::Load(*this, GetPath(), serialisation_type); 
    //return Main_Load(*this, GetPath()); 
}; 
virtual auto SaveDataset(AUX::DATA::SerializationType serialisation_type=AUX::DATA::SerializationType::Xml) const -> bool { 
    return AUX::DATA::Save(*this, GetPath(), serialisation_type); // the ERROR was here mit 'this' passed and not '*this' so it saved but the load method (four lines up) did not work in conjunction with boost::serialization 
    //return Main_Save(*this, GetPath()); 
}; 

我花了出汗的三天哭三夜,使升壓的示例代碼::序列化我可以爲未來的工作做好準備。該文件是可怕的,所以我想與公衆分享代碼。

這裏是升壓:: serialiazation與繼承的完整的例子,在所有數據類==平等的測試,並與兩個測試用例在main():

http://coliru.stacked-crooked.com/a/e241bda2210e3d02

它可以保存和加載二進制,文本和XML(更改main()的第一行)。

Additionaly它具有存儲多個數據集的地圖和存儲/加載它們變成從單獨的文件中的所有一次/一個可選的經理(見第二個用例的main())。

有些委員認爲,你可以看到替代代碼應太文本和二進制格式:

template <class T> 
void Dataset1::save_impl_text_binary(T& archive, const unsigned int version) const { 
    archive & boost::serialization::base_object<Dataset0>(*this); 
    archive & m_a1_; 
    archive & m_b1_; 
/* archive & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Dataset0); 
    archive & BOOST_SERIALIZATION_NVP(m_a1_); 
    archive & BOOST_SERIALIZATION_NVP(m_b1_); */ 
}