3

我计划制作像 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.
}

你可以帮帮我吗?如何从基指针到派生指针?

4

1 回答 1

0

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

于 2011-01-20T16:25:57.880 回答