2011-01-20 36 views
3

我已經計劃進行自定義歸檔喜歡的boost ::檔案:: xml_oachive,我發現在升壓/庫/系列化/例如文件夾很好的例子。如何製作解析指針存檔?

參見下面的代碼(存在上述目錄):

// 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. 
} 

你能幫我嗎?我如何從基指針到派生指針?

+0

我找到了解決辦法。 simple_log_archive.hpp只是基本mpl流程的示例。如果你想製作一個可自動強制轉換的自定義壓縮文件,首先需要繼承detail :: common_oarchive或者detail :: common_iarchive並實現。參考basic_binary/text/xml_archive。 detail :: common_archive已經實現了一個指針轉換過程。 其次,限定BOOST_CLASS_EXPORT(導出)。這個宏是make guid,這個guid詳細使用:: common_archive來尋找「真正的類型」。 – 2011-01-21 00:57:34

+0

最後,我還是不知道爲什麼text_oarchive的可能不register_type(),但你必須註冊檔案類型。(ar.register_type ()) – 2011-01-21 01:01:47

回答

0

如果你需要的是如何將一個基類指針轉換爲派生類,那麼這應該這樣做:dynamic_cast<Derived*>(base)