20 Mart 2018 Salı

variant recursive_variant

Giriş
Şu satırı dahil ederiz.
#include <boost/variant.hpp>
#include <boost/variant/recursive_wrapper.hpp>
#include <boost/variant/variant.hpp>
Örnek
Şöyle yaparız. Burada variant int veya std::map olabilir.
using Leaf    = int;
using Node    = boost::make_recursive_variant< Leaf,
  std::map<std::string, boost::recursive_variant_> >::type;
using SubTree = std::map<std::string, Node>;

static Node sample = SubTree {
    { "simple", 100 },
    { "compound", SubTree { 
              { "first", 200 },
              { "second", 300 },
          }, },
    { "deep", SubTree {  
            { "nested", SubTree { 
                    { "compound", SubTree { 
                              { "buried", 400 },
                              { "secrets", 500 },
                          },
                    },
                },
            },
        },
    }
};
Dolaşmak için şöyle yaparız.
int lookup(Node const& context, std::deque<std::string> path) {
  if (path.empty())
    return boost::get<Leaf>(context);

  auto& sub = boost::get<SubTree>(context);

  auto element = path.front();
  path.pop_front();

  try {
    return lookup(sub.at(element), std::move(path));
  } catch(std::out_of_range const& e) {
    throw std::runtime_error("'" + element + "' not found");
  }
}
Örnek
Şöyle yaparız.
using String  = std::string;
using Integer = long;
using Float   = double;
using Boolean = bool;
using Key     = std::string;
using Path    = std::string;
using Value   = boost::make_recursive_variant<
      Null, 
      String, 
      Integer, 
      Float, 
      Boolean,
      std::unordered_map<Key, boost::recursive_variant_>, // Object
      std::vector<boost::recursive_variant_>              // Array
>::type;
using Object = std::unordered_map<Key, Value>;
using Array = boost::variant<Value>;
Örnek
Şöyle yaparız. boost::blank boş bir struct
typedef boost::make_recursive_variant<
    boost::blank,
    std::string,
    std::vector< std::string >,
    std::vector< int32_t >,
    std::vector< int64_t >,
    std::vector< double >,
    std::vector< std::complex<double> >,
    std::unordered_map< std::string, boost::recursive_variant_ > 
>::type Variant;


Hiç yorum yok:

Yorum Gönder