BOOST:使用字符串

时间:2015-10-19 17:13:26

标签: c++ boost import export

目前我正在使用Boost注册和序列化一些类。为每个类使用以下代码:

BOOST_CLASS_EXPORT(Namespace::ClassName)

现在我的问题是,是否有可能使用Namespace :: ClassName引用此类,以便我可以再次导入/使用/查找该类?到目前为止,我对Boost文档的搜索没有任何结果。感谢

编辑:

从下面尝试代码时,会发生以下错误:

原因:引发了一个提升异常:在函数T * boost :: serialization :: factory(__ va_list_tag *)中的/usr/include/boost/serialization/factory.hpp:38 [使用T = Namespace :: ClassName; int N = 0]以下表达式的计算结果为false:false

Backtrace:

1       0x7fae7fbb7528 boost::assertion_failed(char const*, char const*, char const*, long) + 275
2             0x743147 Namespace::ClassName* boost::serialization::factory<Namespace::ClassName, 0>(__va_list_tag*) + 37
3             0x739bc5 boost::seri

1 个答案:

答案 0 :(得分:1)

我能够从

中拼凑出来

<强> Live On Coliru

#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/serialization.hpp>

struct Base {
    virtual ~Base() = default;
    template <typename Ar> void serialize(Ar&, unsigned) { }
};

struct MyStruct : Base {
    template <typename Ar> void serialize(Ar& ar, unsigned) { ar & boost::serialization::base_object<Base>(*this); }
};

#if 1
    BOOST_CLASS_EXPORT_GUID(Base    , "98e8e3ea-a14a-4875-89d9-6dc58e10002c")
    BOOST_CLASS_EXPORT_GUID(MyStruct, "97e71ba2-8cb9-45b4-803f-809676925e5c")
#else
    BOOST_CLASS_EXPORT(Base)
    BOOST_CLASS_EXPORT(MyStruct)
#endif

BOOST_SERIALIZATION_FACTORY_0(MyStruct)

int main() {
    using namespace boost::serialization;

    std::string s = guid<MyStruct>();
    std::cout << s << "\n";

    extended_type_info const* eti = extended_type_info::find(s.c_str());

    Base* p = static_cast<MyStruct*>(eti->construct());
    std::cout << std::boolalpha << (!!p) << "\n";
}

打印:

97e71ba2-8cb9-45b4-803f-809676925e5c
true

或(if you change #if 1 to #if 0):

MyStruct
true