1

I am using boost recursive variant to store the variant data which I want to encode using msgpack for which I need to get the raw data to pass into encode() function (see below).

I tried three different options in encode() function below but doesn't work. What are the alternates?

typedef std::vector<boost::recursive_variant_> vector_rvariant_t; 
typedef std::map<std::string, boost::recursive_variant_> map_rvariant_t;

typedef boost::make_recursive_variant <bool, boost::uint8_t, boost::uint32_t, 
        boost::int32_t, double, std::string, boost::uuids::uuid,  
        vector_rvariant_t, map_rvariant_t > ::type rvariant_type;

/**
 Wrapper class for boost::make_recuverise_variant<>::type
*/
class rvariant {
public:
   // encode the _data to msgpack buffer 
   //NEED HELP for this function.
    void encode(msgpack::sbuf& sbuf) {
       // msgpack::pack(sbuf, (*type_)data_);
       // msgpack::pack(sbuf, boost::get<typeid(data_)>(data_));
       // msgpack::pack(sbuf, boost::get<*type_>(data_));
    }

    // constructor 
    explicit template <typename T> rvariant(const T& data) {
       data_ = data;
       type_ =  (std::type_info*)&typeid(data);
    }

    // operator=  
   template <typename T> rvariant& operator=(const T& data) {
       data_ = data;
       type_ = (std::type_info*)&typeid(data);
       return *this;
   }

    // get the data 
   template<typename T> T get() {
       return boost::get< T >(data_);
   }

private:
  rvariant_type data_;
  std::type_info* type_;

};
4

1 回答 1

1

我不认为您使用std::type_info的方式与 Boost::Variant 一起使用。

主意:

  1. 使用与此处提供的代码类似的代码来包装您的调用以对您自己的标签进行编码。通过使用访问者,您基本上将自己限制在 Boost.Variant 库的公共界面中。替代方案:使用variant.which

  2. 不要试图捎带 boost::variant 的内部标记和数据存储,因为它以后可能会改变。请记住,Boost.Variant 可能会根据编译器功能和模板参数的属性(例如,对引用类型进行特殊处理)以不同的方式分配其内部数据。相反,分别对标签进行编码(如第一步),然后分别对(键入的)数据进行编码。

我希望这会有所帮助。我想简短的版本是这样的:您的方法虽然比我描述的更直接,但更难正确,因为您依赖于 Variant 的内部结构。

编辑:我查看了 Boost.Serialization 源代码。它可能会有所帮助:http ://svn.boost.org/svn/boost/trunk/boost/serialization/variant.hpp

编辑:为了说明(并使答案更加独立),这是 Boost.Serialization 中的访问者的样子(参见上面的链接):

template<class Archive>
struct variant_save_visitor : boost::static_visitor<>  {
  variant_save_visitor(Archive& ar) : m_ar(ar) {}

  template<class T>
  void operator()(T const & value) const {
    m_ar << BOOST_SERIALIZATION_NVP(value);
  }
private:
  Archive & m_ar;
};
于 2011-03-26T04:03:26.657 回答