我有一个外部库的结构,我写了一些非侵入式序列化方法。还有我的这个结构的包装器,我试图将所有依赖从外部结构保留到这个包装器。问题是,所有序列化方法都是模板,因此它们在头文件中定义,并将依赖从外部库传播到序列化包装器的每个人,我正在努力避免。有可能解决这个问题吗?
UPD:最初我有这样的事情:// serialization.h
#include <external_library.h>
template <typename Archive>
void serialize(Archive& archive, ExternalStruct& external_struct, const unsigned int version) {
// ...
}
然后我尝试为特定类型的存档创建序列化函数非模板:
// serialization.h
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
struct ExternalStruct;
void serialize(boost::archive::binary_iarchive& archive, ExternalStruct& external_struct, const unsigned int version);
void serialize(boost::archive::binary_oarchive& archive, ExternalStruct& external_struct, const unsigned int version);
// serialization.cpp
#include <external_library.h>
#include "serialization.h"
void serialize(boost::archive::binary_iarchive& archive, ExternalStruct& external_struct, const unsigned int version) {
// ...
}
void serialize(boost::archive::binary_oarchive& archive, ExternalStruct& external_struct, const unsigned int version) {
// ...
}
但后来我收到很多编译错误:
no type named 'type' in 'struct boost::mpl::greater<boost::serialization::tracking_level<ExternalStruct>, mpl_::int_<0> >'
BOOST_STATIC_WARNING(typex::value);
答案 0 :(得分:3)
如果您在头文件中保留模板声明,我认为您将获得更好的代码
// serialization.h
#include <external_library.h>
struct ExternalStruct;
template <typename Archive>
void serialize(Archive& archive, ExternalStruct& external_struct, const unsigned int version);
然后将模板实现放入源文件中,隐藏详细信息:
// serialization.cpp
#include "serialization.h"
#include <external_library.h>
template <typename Archive>
void serialize(Archive& archive, ExternalStruct& external_struct, const unsigned int version)
{
// ... details here
}
最后,您为计划使用的特定存档类型添加“显式实例化”。此代码与上面的源文件相同。
// serialization.cpp continued
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
template void serialize(boost::archive::binary_iarchive& archive,
ExternalStruct& external_struct, const unsigned int version); // explicit instantiation.
template void serialize(boost::archive::binary_oarchive& archive,
ExternalStruct& external_struct, const unsigned int version); // explicit instantiation.
答案 1 :(得分:0)
当然这是可能的。 您可以为要使用的每种方法编写自己的函数。
维护非常难看,但这是一种无需任何模板即可使用的方法。