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 に答える