ALPSCore reference
hdf5_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_HDF5_VARIANT_HPP_e36c01f03a8b4756a0a0a098877618dd
15 #define ALPS_PARAMS_HDF5_VARIANT_HPP_e36c01f03a8b4756a0a0a098877618dd
16 
17 #include <alps/hdf5/archive.hpp>
18 #include <alps/hdf5/vector.hpp>
19 #include <alps/hdf5/pair.hpp>
20 
22 
23 #include <cassert>
24 
25 namespace alps {
26  namespace hdf5 {
27 
28  namespace detail {
30  struct to_archive {
32  std::string context_;
33 
34  to_archive(alps::hdf5::archive& ar) : ar_(ar), context_(ar.get_context()) {}
35 
36  template <typename T>
37  void operator()(const T& val) {
38  ar_[context_] << val;
39  }
40  };
41 
43  struct from_archive {
45  std::string context_;
46 
48  template <typename T>
49  inline bool can_read(const T*)
50  {
51  return is_native_type<T>::value
52  && ar_.is_datatype<T>(context_)
53  && ar_.is_scalar(context_);
54  }
55 
57  template <typename T>
58  bool can_read(const std::vector<T>*)
59  {
60  return is_native_type<T>::value
61  && ar_.is_datatype<T>(context_)
62  && !ar_.is_scalar(context_);
63  }
64 
65  from_archive(alps::hdf5::archive& ar)
66  : ar_(ar), context_(ar.get_context())
67  {}
68 
69  template <typename T>
70  boost::optional<T> operator()(const T*)
71  {
72  boost::optional<T> maybe_val;
73  if (can_read((T*)0)) {
74  T val;
75  ar_[context_] >> val;
76  maybe_val=val;
77  }
78  return maybe_val;
79  }
80  };
81 
82  typedef alps::detail::variant_serializer<alps::params_ns::detail::dict_all_types,
83  to_archive, from_archive> var_serializer;
84  typedef var_serializer::variant_type variant_type;
85 
86  } // detail::
87 
89  template <typename MPLSEQ>
90  inline void write_variant(alps::hdf5::archive& ar, const typename boost::make_variant_over<MPLSEQ>::type& var)
91  {
92  detail::to_archive consumer(ar);
93  detail::var_serializer::consume(consumer, var);
94  }
95 
97  template <typename MPLSEQ>
98  inline
99  typename boost::make_variant_over<MPLSEQ>::type read_variant(alps::hdf5::archive& ar)
100  {
101  detail::from_archive producer(ar);
102  return detail::var_serializer::produce(producer);
103  }
104 
105  } // mpi::
106 } // alps::
107 
108 #endif /* ALPS_PARAMS_HDF5_VARIANT_HPP_e36c01f03a8b4756a0a0a098877618dd */
bool is_scalar(std::string path) const
Definition: archive.cpp:199
bool is_datatype(std::string path) const
Definition: archive.hpp:138
Header for boost::variant serialization.
boost::make_variant_over< MPLSEQ >::type read_variant(alps::hdf5::archive &ar)
loading of a boost::variant over MPL type sequence MPLSEQ
void write_variant(alps::hdf5::archive &ar, const typename boost::make_variant_over< MPLSEQ >::type &var)
saving of a boost::variant over MPL type sequence MPLSEQ