TRIQS/TRIQS 4.0.0
Researching Interacting Quantum Systems
Loading...
Searching...
No Matches
variant_serialize.hpp
Go to the documentation of this file.
1// Copyright (c) 2015-2018 Commissariat à l'énergie atomique et aux énergies alternatives (CEA)
2// Copyright (c) 2015-2018 Centre national de la recherche scientifique (CNRS)
3// Copyright (c) 2018-2020 Simons Foundation
4// Copyright (c) 2015 Igor Krivenko
5//
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10//
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15//
16// You may obtain a copy of the License at
17// https://www.gnu.org/licenses/gpl-3.0.txt
18//
19// Authors: Igor Krivenko, Olivier Parcollet, Nils Wentzell
20
25
26#pragma once
27
28#include <boost/serialization/split_free.hpp>
29
30#include <variant>
31
32namespace boost::serialization {
33
38
39 // Visitor that saves the held alternative to a Boost archive.
40 template <typename Archive> struct variant_serialize_saver {
41 Archive &ar; // NOLINT
42 variant_serialize_saver(Archive &ar) : ar(ar) {}
43 template <typename T> void operator()(T x) { ar << x; }
44 };
45
46 // Visitor that loads an alternative from a Boost archive (optionally placement-new-constructing the slot first).
47 template <typename Archive> struct variant_serialize_loader {
48 Archive &ar; // NOLINT
49 bool initialize;
50 variant_serialize_loader(Archive &ar, bool initialize) : ar(ar), initialize(initialize) {}
51 template <typename T> void operator()(T &x) {
52 if (initialize) ::new (&x) T();
53 ar >> x;
54 }
55 };
56
68 template <typename Archive, typename... Ts> void save(Archive &ar, std::variant<Ts...> const &v, [[maybe_unused]] const unsigned int version) {
69 ar << v.type_id;
70 visit(variant_serialize_saver<Archive>(ar), v);
71 }
72
84 template <typename Archive, typename... Ts> void load(Archive &ar, std::variant<Ts...> &v, [[maybe_unused]] const unsigned int version) {
85 int new_type_id{};
86 ar >> new_type_id;
87 if (v.type_id != new_type_id) {
88 v.destroy();
89 v.type_id = new_type_id;
90 visit(variant_serialize_loader<Archive>(ar, true), v);
91 } else
92 visit(variant_serialize_loader<Archive>(ar, false), v);
93 }
94
96
97} // namespace boost::serialization
const_view_type operator()() const
Make a const view of *this.
void load(Archive &ar, std::variant< Ts... > &v, const unsigned int version)
Deserialize a std::variant.
void save(Archive &ar, std::variant< Ts... > const &v, const unsigned int version)
Serialize a std::variant.