预先定义一个typedefed boost :: variant

时间:2013-03-05 08:57:21

标签: c++ boost

如何进行以下编译:

typedef std::pair<std::string, Container> Structure;

typedef boost::variant<std::vector<int>, std::vector<std::string>, std::vector<Structure> > Container;

1 个答案:

答案 0 :(得分:3)

这是Angew的解决方案,通过liveworkspace.org/code/3BDk6v$0链接到上面

#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <boost/variant.hpp>


typedef boost::make_recursive_variant<
         std::vector<int>,
         std::vector<std::string>,
         std::vector< std::pair<std::string, boost::recursive_variant_> >
         >::type Container;

typedef std::pair<std::string, Container> Structure;

struct printer: boost::static_visitor<>
{
   void operator()(const std::vector<int>& vec) const
   {
      for(const auto elem : vec)
         std::cout << elem << std::endl;
   }
   void operator()(const std::vector<std::string>& vec) const
   {
      for(const auto& elem : vec)
         std::cout << elem << std::endl;
   }
   void operator()(const std::vector<Structure>& vec) const
   {
      for(const auto& elem : vec)
      {
         std::cout << "First:" << std::endl;
         std::cout << elem.first << std::endl;
         std::cout << "Second:" << std::endl;
         boost::apply_visitor(*this,elem.second);
      }
   }
};


int main()
{
   std::vector<Container> c_vec;
   std::vector<int> int_vec;
   int_vec.push_back(1);
   int_vec.push_back(2);
   Container c(int_vec);
   Structure s=std::make_pair(std::string("name"),c);
   std::vector<Structure> s_vec;
   s_vec.push_back(s);
   c_vec.push_back(int_vec);
   c_vec.push_back(s_vec);

   for(auto const& elem : c_vec)
      boost::apply_visitor(printer(),elem);   
   return 0;
}