variant.h
Go to the documentation of this file.
1 //
2 // Created by Eduard Valeyev on 6/22/21.
3 //
4 
5 #ifndef TTG_SERIALIZATION_STD_VARIANT_H
6 #define TTG_SERIALIZATION_STD_VARIANT_H
7 
9 
10 #ifdef TTG_SERIALIZATION_SUPPORTS_MADNESS
11 // MADNESS does not supports std::variant serialization
12 #endif
13 
14 #ifdef TTG_SERIALIZATION_SUPPORTS_BOOST
15 
16 namespace boost {
17  namespace serialization {
18 
19  namespace detail {
20 
21  template <typename Archive, typename... Ts, std::size_t I0, std::size_t... Is>
22  Archive& variant_load_impl(Archive& ar, std::variant<Ts...>& v, std::size_t which,
23  std::index_sequence<I0, Is...>) {
24  constexpr bool writing = ttg::detail::is_output_archive_v<Archive>;
25  static_assert(!writing);
26  if (which == I0) {
27  using type = std::variant_alternative_t<I0, std::variant<Ts...>>;
28  if (!std::is_same_v<type, std::monostate>) {
29  type value;
30  ar& value;
31  v.template emplace<I0>(std::move(value));
32  }
33  } else {
34  if constexpr (sizeof...(Is) == 0)
35  throw std::logic_error(
36  "boost::serialization::detail::variant_load_impl(ar,v,idx,idxs): idx is not present in idxs");
37  else
38  return variant_load_impl(ar, v, which, std::index_sequence<Is...>{});
39  }
40  return ar;
41  }
42 
43  } // namespace detail
44 
45  template <typename Archive, typename... Ts>
46  Archive& serialize(Archive& ar, std::variant<Ts...>& t, const unsigned int version) {
47  constexpr bool writing = ttg::detail::is_output_archive_v<Archive>;
48  const auto index = t.index();
49  ar& index;
50  // to write visit the current alternative
51  if constexpr (writing) {
52  std::visit(
53  [&ar](const auto& v) {
54  if constexpr (!std::is_same_v<std::decay_t<decltype(v)>, std::monostate>) ar& v;
55  },
56  t);
57  } else // reading by recursive traversal until found index
58  detail::variant_load_impl(ar, t, index, std::make_index_sequence<sizeof...(Ts)>{});
59  return ar;
60  }
61 
62  } // namespace serialization
63 } // namespace boost
64 
65 namespace ttg::detail {
66  template <typename Archive, typename... Ts>
67  inline static constexpr bool is_stlcontainer_boost_serializable_v<Archive, std::variant<Ts...>> =
68  (is_boost_serializable_v<Archive, Ts> && ...);
69  template <typename Archive, typename... Ts>
70  inline static constexpr bool is_stlcontainer_boost_serializable_v<Archive, const std::variant<Ts...>> =
71  (is_boost_serializable_v<Archive, const Ts> && ...);
72 } // namespace ttg::detail
73 
74 #endif // TTG_SERIALIZATION_SUPPORTS_BOOST
75 
76 #endif // TTG_SERIALIZATION_STD_TUPLE_H
typename make_index_sequence_t< I... >::type make_index_sequence
std::array< int, 3 > version()
Definition: version.cc:4