【问题标题】:passing *this to template function with boost::serialization code makes error使用 boost::serialization 代码将 *this 传递给模板函数会出错
【发布时间】:2017-07-22 15:36:16
【问题描述】:

我有一个从文本文件加载的免费模板函数:

// 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

但是当我从成员函数调用这个模板函数时,我得到一个错误“what(): input stream error”:

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 但不能传递 *this?我想与 *this 结合使用有问题:

archive_text & dataset;

编辑 我已经回答了我自己的问题。见下文。

【问题讨论】:

标签: c++ templates pass-by-reference boost-serialization


【解决方案1】:

我在我的代码中发现了错误。

错误出现在我的代码的第 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());
};

我花了三天的汗水和三个晚上的哭泣,才在 boost::serialization 中编写了一个示例代码,可以用于我未来的工作。文档很糟糕,所以我想与公众分享代码。

这里是 boost::serialization 的完整示例,在所有数据类中使用 == 来测试相等性,并在 main() 中使用两个测试用例:

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

它可以保存和加载二进制、文本和xml(在main()中更改第一行)。

此外,它还有一个可选的管理器,可以将多个数据集存储在一个地图中,并同时将它们存储/加载到单独的文件中(参见 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_); */
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2011-12-07
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    相关资源
    最近更新 更多