ALPSCore reference
serialize_variant.hpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1998-2018 ALPS Collaboration. See COPYRIGHT.TXT
3  * All rights reserved. Use is subject to license terms. See LICENSE.TXT
4  * For use in publications, see ACKNOWLEDGE.TXT
5  */
6 
14 #ifndef ALPS_PARAMS_SERIALIZE_VARIANT_HPP_d116b6a1742b418f851e0dbb87004644
15 #define ALPS_PARAMS_SERIALIZE_VARIANT_HPP_d116b6a1742b418f851e0dbb87004644
16 
17 #include <boost/variant.hpp>
18 #include <boost/mpl/for_each.hpp>
19 #include <stdexcept>
20 #include <boost/optional.hpp>
21 
22 namespace alps {
23  namespace detail {
24 
26  template <typename MPLSEQ, typename CONSUMER, typename PRODUCER>
27  class variant_serializer {
28  public:
29  typedef typename boost::make_variant_over<MPLSEQ>::type variant_type;
30  typedef CONSUMER consumer_type;
31  typedef PRODUCER producer_type;
32 
33  private:
35  struct consume_visitor : public boost::static_visitor<> {
36  consumer_type& consumer_;
37 
38  consume_visitor(consumer_type& consumer) : consumer_(consumer) {}
39 
40  template <typename T>
41  void operator()(const T& val) const
42  {
43  consumer_(val);
44  }
45  };
46 
48  struct maker {
49  producer_type& producer_;
50  variant_type& var_;
51 
52  maker(producer_type& producer, variant_type& var)
53  : producer_(producer), var_(var)
54  { }
55 
56  // Always assigns --- therefore, applies last successful outcome!
57  template <typename T>
58  void operator()(const T&) {
59  boost::optional<T> maybe_val=producer_((T*)0);
60  if (maybe_val) var_=*maybe_val;
61  }
62  };
63 
64  public:
65 
67  static void consume(consumer_type& consumer, const variant_type& var)
68  {
69  boost::apply_visitor(consume_visitor(consumer), var);
70  }
71 
73  static variant_type produce(producer_type& producer)
74  {
75  variant_type var;
76  boost::mpl::for_each<MPLSEQ>(maker(producer, var));
77  return var;
78  }
79  };
80 
81  } // detail::
82 } // alps::
83 
84 #endif /* ALPS_PARAMS_SERIALIZE_VARIANT_HPP_d116b6a1742b418f851e0dbb87004644 */
F::result_type apply_visitor(F &visitor, dictionary::const_iterator it)
Const-access visitor to a value by an iterator.
Definition: dictionary.hpp:110