openPMD-api
 
Loading...
Searching...
No Matches
Variant.hpp
1/* Copyright 2017-2025 Fabian Koller, Axel Huebl, Franz Poeschel
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 <any>
24#include <cstddef>
25#include <type_traits>
26
27namespace openPMD
28{
29namespace auxiliary
30{
38 template <class T_DTYPES, typename... variant_types>
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:
47 {};
48 static constexpr from_basic_type_tag from_basic_type =
51 {};
52 static constexpr from_any_tag from_any = from_any_tag{};
53 template <typename U>
54 Variant(from_basic_type_tag, U);
55
56 Variant(from_any_tag, std::any);
57
65 template <typename U>
66 Variant(U u);
67
76 template <typename U>
77 [[nodiscard]] U const &get() const;
78
83 template <typename variant_t>
84 [[nodiscard]] variant_t const &getVariant() const
85 {
86 return *std::any_cast<variant_t>(&m_data);
87 }
88
89 [[nodiscard]] std::any const &getAny() const
90 {
91 return m_data;
92 }
93
98 [[nodiscard]] size_t index() const;
99
100 T_DTYPES dtype;
101
102 private:
103 std::any m_data;
104 };
105
106 /*
107 * Helper type for std::visit,
108 * see https://en.cppreference.com/w/cpp/utility/variant/visit
109 */
110 template <class... Ts>
111 struct overloaded : Ts...
112 {
113 using Ts::operator()...;
114 };
115 template <class... Ts>
116 overloaded(Ts...) -> overloaded<Ts...>;
117} // namespace auxiliary
118} // namespace openPMD
Generic object to store a set of datatypes in without losing type safety.
Definition Variant.hpp:40
U const & get() const
Retrieve a stored specific object of known datatype with ensured type-safety.
variant_t const & getVariant() const
Retrieve the stored generic object.
Definition Variant.hpp:84
Variant(U u)
Construct a lightweight wrapper around a generic object that indicates the concrete datatype of the s...
Definition Variant.cpp:52
size_t index() const
Retrieve the index of the alternative that is currently been held.
Definition Variant.cpp:66
Public definitions of openPMD-api.
Definition Date.cpp:29
Definition Variant.hpp:112