9d1b37de28a752e37be25b34dd4e2c27b4aeb332
[alexxy/gromacs.git] / src / gromacs / utility / variant.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2016,2017, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \libinternal \file
36  * \brief
37  * Declares gmx::Variant.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \inlibraryapi
41  * \ingroup module_utility
42  */
43 #ifndef GMX_UTILITY_VARIANT_H
44 #define GMX_UTILITY_VARIANT_H
45
46 #include <memory>
47 #include <string>
48 #include <type_traits>
49 #include <typeindex>
50 #include <typeinfo>
51 #include <utility>
52
53 #include "gromacs/utility/gmxassert.h"
54
55 namespace gmx
56 {
57
58 /*! \libinternal \brief
59  * Represents a dynamically typed value of an arbitrary type.
60  *
61  * To create a variant, either initialize it as empty, or with the create()
62  * method (or the equivalent constructor, if the type parameter can be deduced
63  * and is clear to the reader from the context).
64  *
65  * To query the type of the contents in the variant, use isEmpty(), type(), and
66  * isType().
67  *
68  * To access the value, you need to know the type as a compile-time constant
69  * (e.g., through branching based on isType()), and then use cast() or
70  * tryCast().
71  *
72  * Methods in this class do not throw unless otherwise indicated.
73  *
74  * This provides essentially the same functionality as boost::any.
75  *
76  * \ingroup module_utility
77  */
78 class Variant
79 {
80     public:
81         /*! \brief
82          * Creates a variant that holds the given value.
83          *
84          * \throws std::bad_alloc if out of memory.
85          *
86          * This method allows explicitly specifying the template argument,
87          * contrary to the templated constructor.
88          */
89         template <typename T>
90         static Variant create(const T &value) { return Variant(value); }
91         /*! \brief
92          * Creates a variant that holds the given value.
93          *
94          * \throws std::bad_alloc if out of memory.
95          *
96          * In addition to allowing specifying the template argument, this
97          * method avoids copying when move-construction is possible.
98          */
99         template <typename T>
100         static Variant create(T &&value) { return Variant(std::move(value)); }
101
102         //! Creates an empty variant value.
103         Variant() {}
104         /*! \brief
105          * Creates a variant that holds the given value.
106          *
107          * \throws std::bad_alloc if out of memory.
108          */
109         template <typename T>
110         explicit Variant(const T &value)
111             : content_(new Content<typename std::decay<T>::type>(value))
112         {
113         }
114         /*! \brief
115          * Creates a variant that holds the given value.
116          *
117          * \throws std::bad_alloc if out of memory.
118          */
119         template <typename T>
120         explicit Variant(T &&value)
121             : content_(new Content<typename std::decay<T>::type>(std::move(value)))
122         {
123         }
124         /*! \brief
125          * Creates a deep copy of a variant.
126          *
127          * \throws std::bad_alloc if out of memory.
128          */
129         Variant(const Variant &other) : content_(other.cloneContent()) {}
130         //! Move-constructs a variant.
131         Variant(Variant &&other) noexcept : content_(std::move(other.content_)) {}
132         /*! \brief
133          * Assigns the variant.
134          *
135          * \throws std::bad_alloc if out of memory.
136          */
137         Variant &operator=(const Variant &other)
138         {
139             content_.reset(other.cloneContent());
140             return *this;
141         }
142         //! Move-assigns the variant.
143         Variant &operator=(Variant &&other) noexcept
144         {
145             content_ = std::move(other.content_);
146             return *this;
147         }
148
149         //! Whether any value is stored.
150         bool isEmpty() const { return content_ == nullptr; }
151         //! Returns the dynamic type of the value that is currently stored.
152         std::type_index type() const
153         {
154             const std::type_info &info
155                 = !isEmpty() ? content_->typeInfo() : typeid(void);
156             return std::type_index(info);
157         }
158         //! Returns whether the type stored matches the template parameter.
159         template <typename T>
160         bool isType() const
161         {
162             return !isEmpty() && content_->typeInfo() == typeid(T);
163         }
164
165         /*! \brief
166          * Tries to get the value as the given type.
167          *
168          * \tparam T  Type to get.
169          * \returns Pointer to the value, or nullptr if the type does not match
170          *     the stored value.
171          */
172         template <typename T>
173         const T *tryCast() const
174         {
175             return isType<T>() ? &static_cast<Content<T> *>(content_.get())->value_ : nullptr;
176         }
177         /*! \brief
178          * Gets the value when the type is known.
179          *
180          * \tparam T  Type to get (which must match what the variant stores).
181          *
182          * Asserts if the variant is empty or does not contain the requested type.
183          */
184         template <typename T>
185         const T &cast() const
186         {
187             const T *value = tryCast<T>();
188             GMX_RELEASE_ASSERT(value != nullptr, "Cast to incorrect type");
189             return *value;
190         }
191         /*! \brief
192          * Tries to get the value as the given type as a non-const pointer.
193          *
194          * \tparam T  Type to get.
195          * \returns Pointer to the value, or nullptr if the type does not match
196          *     the stored value.
197          *
198          * This method allows modifying the value in-place, which is useful
199          * with more complicated data structures.
200          */
201         template <typename T>
202         T *tryCastRef()
203         {
204             return isType<T>() ? &static_cast<Content<T> *>(content_.get())->value_ : nullptr;
205         }
206         /*! \brief
207          * Gets the value when the type is known as a modifiable reference.
208          *
209          * \tparam T  Type to get (which must match what the variant stores).
210          *
211          * Asserts if the variant is empty or does not contain the requested type.
212          */
213         template <typename T>
214         T &castRef()
215         {
216             T *value = tryCastRef<T>();
217             GMX_RELEASE_ASSERT(value != nullptr, "Cast to incorrect type");
218             return *value;
219         }
220
221     private:
222         class IContent
223         {
224             public:
225                 virtual ~IContent() {}
226                 virtual const std::type_info &typeInfo() const = 0;
227                 virtual IContent *clone() const                = 0;
228         };
229
230         template <typename T>
231         class Content : public IContent
232         {
233             public:
234                 explicit Content(const T &value) : value_(value) {}
235                 explicit Content(T &&value) : value_(std::move(value)) {}
236
237                 virtual const std::type_info &typeInfo() const { return typeid(T); }
238                 virtual IContent *clone() const { return new Content(value_); }
239
240                 T value_;
241         };
242
243         //! Creates a deep copy of the content.
244         IContent *cloneContent() const
245         {
246             return content_ != nullptr ? content_->clone() : nullptr;
247         }
248
249         std::unique_ptr<IContent> content_;
250 };
251
252 //! \cond libapi
253 /*! \brief
254  * Converts a Variant value to a string.
255  *
256  * As the name suggests, only some types of "simple" values (such as int) are
257  * supported.  Asserts for unsupported types.
258  *
259  * \ingroup module_utility
260  */
261 std::string simpleValueToString(const Variant &value);
262 //! \endcond
263
264 } // namespace gmx
265
266 #endif