如何使存档成为解析指针?

时间:2011-01-20 06:19:18

标签: c++ boost boost-serialization

我打算像boost :: archive :: xml_oachive那样制作自定义存档,我在boost / libs / serialization / example文件夹中找到了很好的例子。

参见下一个代码(上面的目录中):

// simple_log_archive.hpp
...
class simple_log_archive
{
    ...
    template <class Archive>
    struct save_primitive
    {
        template <class T>
        static void invoke(Archive& ar, const T& t)
        {
            // streaming
        }
    };

    template <class Archive>
    struct save_only
    {
        template <class T>
        static void invoke(Archive& ar, const T& t)
        {
            boost::serialization::serialize_adl(ar, const_cast<T&>(t),
                ::boost::serialization::version<T>::value);
        }
    };

    template <class T>
    void save(const T& t)
    {
        typedef BOOST_DEDUCED_TYPENAME boost::mpl::eval_if<boost::is_enum<T>,
            boost::mpl::identity<save_enum_type<simple_log_archive> >,
        //else
        BOOST_DEDUCED_TYPENAME boost::mpl::eval_if<
            // if its primitive
                boost::mpl::equal_to<
                    boost::serialization::implementation_level<T>,
                    boost::mpl::int_<boost::serialization::primitive_type>
                >,
                boost::mpl::identity<save_primitive<simple_log_archive> >,
        // else
            boost::mpl::identity<save_only<simple_log_archive> >
        > >::type typex;
        typex::invoke(*this, t);
    }  
public:
    // the << operators 
    template<class T>
    simple_log_archive & operator<<(T const & t){
        m_os << ' ';
        save(t);
        return * this;
    }
    template<class T>
    simple_log_archive & operator<<(T * const t){
        m_os << " ->";
        if(NULL == t)
            m_os << " null";
        else
            *this << * t;
        return * this;
    }
    ...
};

同样,我制作了自定义存档。但我和上面的代码不是自动转换派生指针的基指针。例如,

Base* base = new Derived;
{
    boost::archive::text_oarchive ar(std::cout);
    ar << base;// Base pointer is auto casted to derived pointer! It's fine.
}

{
    simple_log_archive ar;
    ar << base;// Base pointer is not auto casting. This is my problem.
}
你可以帮帮我吗?如何从基指针到派生指针?

1 个答案:

答案 0 :(得分:0)

如果您只需要将基类指针转换为派生类,那么应该这样做:dynamic_cast<Derived*>(base)