openPMD-api
Variant.hpp
1 /* Copyright 2017-2021 Fabian Koller, Axel Huebl
2  *
3  * This file is part of openPMD-api.
4  *
5  * openPMD-api is free software: you can redistribute it and/or modify
6  * it under the terms of of either the GNU General Public License or
7  * the GNU Lesser 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  * openPMD-api 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 and the GNU Lesser General Public License
15  * for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * and the GNU Lesser General Public License along with openPMD-api.
19  * If not, see <http://www.gnu.org/licenses/>.
20  */
21 #pragma once
22 
23 #include <cstddef>
24 #include <type_traits>
25 #include <variant> // IWYU pragma: export
26 
27 namespace openPMD
28 {
29 namespace auxiliary
30 {
38  template <class T_DTYPES, typename std_variant>
39  class Variant
40  {
41  static_assert(
42  std::is_enum<T_DTYPES>::value,
43  "Datatypes to Variant must be supplied as enum.");
44 
45  public:
46  using resource = std_variant;
54  Variant(resource r) : dtype{static_cast<T_DTYPES>(r.index())}, m_data{r}
55  {}
56 
64  template <typename U>
65  U get() const
66  {
67  return std::get<U>(m_data);
68  }
69 
74  resource getResource() const
75  {
76  return m_data;
77  }
78 
83  constexpr size_t index() const noexcept
84  {
85  return m_data.index();
86  }
87 
88  T_DTYPES dtype;
89 
90  private:
91  resource m_data;
92  };
93 
94  /*
95  * Helper type for std::visit,
96  * see https://en.cppreference.com/w/cpp/utility/variant/visit
97  */
98  template <class... Ts>
99  struct overloaded : Ts...
100  {
101  using Ts::operator()...;
102  };
103  template <class... Ts>
104  overloaded(Ts...) -> overloaded<Ts...>;
105 } // namespace auxiliary
106 } // namespace openPMD
Generic object to store a set of datatypes in without losing type safety.
Definition: Variant.hpp:40
constexpr size_t index() const noexcept
Retrieve the index of the alternative that is currently been held.
Definition: Variant.hpp:83
U get() const
Retrieve a stored specific object of known datatype with ensured type-safety.
Definition: Variant.hpp:65
Variant(resource r)
Construct a lightweight wrapper around a generic object that indicates the concrete datatype of the s...
Definition: Variant.hpp:54
resource getResource() const
Retrieve the stored generic object.
Definition: Variant.hpp:74
Public definitions of openPMD-api.
Definition: Date.cpp:29
Definition: Variant.hpp:100