* include/experimental/any (any::_Storage): Fix alignment of buffer.
[official-gcc.git] / libstdc++-v3 / include / experimental / any
blob7b5e5ecbcbae42735988bd127e41f00895a450b2
1 // <experimental/any> -*- C++ -*-
3 // Copyright (C) 2014-2015 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library.  This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
9 // any later version.
11 // This library 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.
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
23 // <http://www.gnu.org/licenses/>.
25 /** @file experimental/any
26  *  This is a TS C++ Library header.
27  */
29 #ifndef _GLIBCXX_EXPERIMENTAL_ANY
30 #define _GLIBCXX_EXPERIMENTAL_ANY 1
32 #pragma GCC system_header
34 #if __cplusplus <= 201103L
35 # include <bits/c++14_warning.h>
36 #else
38 #include <typeinfo>
39 #include <new>
40 #include <utility>
41 #include <type_traits>
43 namespace std _GLIBCXX_VISIBILITY(default)
45 namespace experimental
47 inline namespace fundamentals_v1
49 _GLIBCXX_BEGIN_NAMESPACE_VERSION
51   /**
52    * @defgroup any Type-safe container of any type
53    * @ingroup experimental
54    *
55    * A type-safe container for single values of value types, as
56    * described in n3804 "Any Library Proposal (Revision 3)".
57    *
58    * @{
59    */
61 #define __cpp_lib_experimental_any 201411
63   /**
64    *  @brief Exception class thrown by a failed @c any_cast
65    *  @ingroup exceptions
66    */
67   class bad_any_cast : public bad_cast
68   {
69   public:
70     virtual const char* what() const noexcept { return "bad any_cast"; }
71   };
73   [[gnu::noreturn]] inline void __throw_bad_any_cast()
74   {
75 #if __cpp_exceptions
76     throw bad_any_cast{};
77 #else
78     __builtin_abort();
79 #endif
80   }
82   /**
83    *  @brief A type-safe container of any type.
84    * 
85    *  An @c any object's state is either empty or it stores a contained object
86    *  of CopyConstructible type.
87    */
88   class any
89   {
90     // Holds either pointer to a heap object or the contained object itself.
91     union _Storage
92     {
93       // This constructor intentionally doesn't initialize anything.
94       _Storage() = default;
96       // Prevent trivial copies of this type, buffer might hold a non-POD.
97       _Storage(const _Storage&) = delete;
98       _Storage& operator=(const _Storage&) = delete;
100       void* _M_ptr;
101       aligned_storage<sizeof(_M_ptr), alignof(void*)>::type _M_buffer;
102     };
104     template<typename _Tp, typename _Safe = is_nothrow_move_constructible<_Tp>,
105              bool _Fits = (sizeof(_Tp) <= sizeof(_Storage))
106                           && (alignof(_Tp) <= alignof(_Storage))>
107       using _Internal = std::integral_constant<bool, _Safe::value && _Fits>;
109     template<typename _Tp>
110       struct _Manager_internal; // uses small-object optimization
112     template<typename _Tp>
113       struct _Manager_external; // creates contained object on the heap
115     template<typename _Tp>
116       using _Manager = conditional_t<_Internal<_Tp>::value,
117                                      _Manager_internal<_Tp>,
118                                      _Manager_external<_Tp>>;
120     template<typename _Tp, typename _Decayed = decay_t<_Tp>>
121       using _Decay = enable_if_t<!is_same<_Decayed, any>::value, _Decayed>;
123   public:
124     // construct/destruct
126     /// Default constructor, creates an empty object.
127     any() noexcept : _M_manager(nullptr) { }
129     /// Copy constructor, copies the state of @p __other
130     any(const any& __other)
131     {
132       if (__other.empty())
133         _M_manager = nullptr;
134       else
135         {
136           _Arg __arg;
137           __arg._M_any = this;
138           __other._M_manager(_Op_clone, &__other, &__arg);
139         }
140     }
142     /**
143      * @brief Move constructor, transfer the state from @p __other
144      *
145      * @post @c __other.empty() (this postcondition is a GNU extension)
146      */
147     any(any&& __other) noexcept
148     {
149       if (__other.empty())
150         _M_manager = nullptr;
151       else
152         {
153           _Arg __arg;
154           __arg._M_any = this;
155           __other._M_manager(_Op_xfer, &__other, &__arg);
156         }
157     }
159     /// Construct with a copy of @p __value as the contained object.
160     template <typename _ValueType, typename _Tp = _Decay<_ValueType>,
161               typename _Mgr = _Manager<_Tp>>
162       any(_ValueType&& __value)
163       : _M_manager(&_Mgr::_S_manage)
164       {
165         _Mgr::_S_create(_M_storage, std::forward<_ValueType>(__value));
166         static_assert(is_copy_constructible<_Tp>::value,
167                       "The contained object must be CopyConstructible");
168       }
170     /// Destructor, calls @c clear()
171     ~any() { clear(); }
173     // assignments
175     /// Copy the state of another object.
176     any& operator=(const any& __rhs)
177     {
178       if (__rhs.empty())
179         clear();
180       else
181         {
182           if (!empty())
183             _M_manager(_Op_destroy, this, nullptr);
184           _Arg __arg;
185           __arg._M_any = this;
186           __rhs._M_manager(_Op_clone, &__rhs, &__arg);
187         }
188       return *this;
189     }
191     /**
192      * @brief Move assignment operator
193      *
194      * @post @c __rhs.empty() (not guaranteed for other implementations)
195      */
196     any& operator=(any&& __rhs) noexcept
197     {
198       if (__rhs.empty())
199         clear();
200       else
201         {
202           if (!empty())
203             _M_manager(_Op_destroy, this, nullptr);
204           _Arg __arg;
205           __arg._M_any = this;
206           __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
207         }
208       return *this;
209     }
211     /// Store a copy of @p __rhs as the contained object.
212     template<typename _ValueType>
213       any& operator=(_ValueType&& __rhs)
214       {
215         *this = any(std::forward<_ValueType>(__rhs));
216         return *this;
217       }
219     // modifiers
221     /// If not empty, destroy the contained object.
222     void clear() noexcept
223     {
224       if (!empty())
225       {
226         _M_manager(_Op_destroy, this, nullptr);
227         _M_manager = nullptr;
228       }
229     }
231     /// Exchange state with another object.
232     void swap(any& __rhs) noexcept
233       {
234         if (empty() && __rhs.empty())
235           return;
237         if (!empty() && !__rhs.empty())
238           {
239             any __tmp;
240             _Arg __arg;
241             __arg._M_any = &__tmp;
242             __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
243             __arg._M_any = &__rhs;
244             _M_manager(_Op_xfer, this, &__arg);
245             __arg._M_any = this;
246             __tmp._M_manager(_Op_xfer, &__tmp, &__arg);
247           }
248         else
249           {
250             any* __empty = empty() ? this : &__rhs;
251             any* __full = empty() ? &__rhs : this;
252             _Arg __arg;
253             __arg._M_any = __empty;
254             __full->_M_manager(_Op_xfer, __full, &__arg);
255           }
256       }
258     // observers
260     /// Reports whether there is a contained object or not.
261     bool empty() const noexcept { return _M_manager == nullptr; }
263 #if __cpp_rtti
264     /// The @c typeid of the contained object, or @c typeid(void) if empty.
265     const type_info& type() const noexcept
266     {
267       if (empty())
268         return typeid(void);
269       _Arg __arg;
270       _M_manager(_Op_get_type_info, this, &__arg);
271       return *__arg._M_typeinfo;
272     }
273 #endif
275     template<typename _Tp>
276       static constexpr bool __is_valid_cast()
277       { return __or_<is_reference<_Tp>, is_copy_constructible<_Tp>>::value; }
279   private:
280     enum _Op {
281         _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer
282     };
284     union _Arg
285     {
286         void* _M_obj;
287         const std::type_info* _M_typeinfo;
288         any* _M_any;
289     };
291     void (*_M_manager)(_Op, const any*, _Arg*);
292     _Storage _M_storage;
294     template<typename _Tp>
295       friend void* __any_caster(const any* __any)
296       {
297         if (__any->_M_manager != &_Manager<decay_t<_Tp>>::_S_manage)
298           return nullptr;
299         _Arg __arg;
300         __any->_M_manager(_Op_access, __any, &__arg);
301         return __arg._M_obj;
302       }
304     // Manage in-place contained object.
305     template<typename _Tp>
306       struct _Manager_internal
307       {
308         static void
309         _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
311         template<typename _Up>
312           static void
313           _S_create(_Storage& __storage, _Up&& __value)
314           {
315             void* __addr = &__storage._M_buffer;
316             ::new (__addr) _Tp(std::forward<_Up>(__value));
317           }
318       };
320     // Manage external contained object.
321     template<typename _Tp>
322       struct _Manager_external
323       {
324         static void
325         _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
327         template<typename _Up>
328           static void
329           _S_create(_Storage& __storage, _Up&& __value)
330           {
331             __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
332           }
333       };
334   };
336   /// Exchange the states of two @c any objects.
337   inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
339   /**
340    * @brief Access the contained object.
341    *
342    * @tparam  _ValueType  A const-reference or CopyConstructible type.
343    * @param   __any       The object to access.
344    * @return  The contained object.
345    * @throw   bad_any_cast If <code>
346    *          __any.type() != typeid(remove_reference_t<_ValueType>)
347    *          </code>
348    */
349   template<typename _ValueType>
350     inline _ValueType any_cast(const any& __any)
351     {
352       static_assert(any::__is_valid_cast<_ValueType>(),
353           "Template argument must be a reference or CopyConstructible type");
354       auto __p = any_cast<add_const_t<remove_reference_t<_ValueType>>>(&__any);
355       if (__p)
356         return *__p;
357       __throw_bad_any_cast();
358     }
360   /**
361    * @brief Access the contained object.
362    *
363    * @tparam  _ValueType  A reference or CopyConstructible type.
364    * @param   __any       The object to access.
365    * @return  The contained object.
366    * @throw   bad_any_cast If <code>
367    *          __any.type() != typeid(remove_reference_t<_ValueType>)
368    *          </code>
369    *
370    * @{
371    */
372   template<typename _ValueType>
373     inline _ValueType any_cast(any& __any)
374     {
375       static_assert(any::__is_valid_cast<_ValueType>(),
376           "Template argument must be a reference or CopyConstructible type");
377       auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
378       if (__p)
379         return *__p;
380       __throw_bad_any_cast();
381     }
383   template<typename _ValueType>
384     inline _ValueType any_cast(any&& __any)
385     {
386       static_assert(any::__is_valid_cast<_ValueType>(),
387           "Template argument must be a reference or CopyConstructible type");
388       auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
389       if (__p)
390         return *__p;
391       __throw_bad_any_cast();
392     }
393   // @}
395   /**
396    * @brief Access the contained object.
397    *
398    * @tparam  _ValueType  The type of the contained object.
399    * @param   __any       A pointer to the object to access.
400    * @return  The address of the contained object if <code>
401    *          __any != nullptr && __any.type() == typeid(_ValueType)
402    *          </code>, otherwise a null pointer.
403    *
404    * @{
405    */
406   template<typename _ValueType>
407     inline const _ValueType* any_cast(const any* __any) noexcept
408     {
409       if (__any)
410         return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
411       return nullptr;
412     }
414   template<typename _ValueType>
415     inline _ValueType* any_cast(any* __any) noexcept
416     {
417       if (__any)
418         return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
419       return nullptr;
420     }
421   // @}
423   template<typename _Tp>
424     void
425     any::_Manager_internal<_Tp>::
426     _S_manage(_Op __which, const any* __any, _Arg* __arg)
427     {
428       // The contained object is in _M_storage._M_buffer
429       auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
430       switch (__which)
431       {
432       case _Op_access:
433         __arg->_M_obj = const_cast<_Tp*>(__ptr);
434         break;
435       case _Op_get_type_info:
436 #if __cpp_rtti
437         __arg->_M_typeinfo = &typeid(_Tp);
438 #endif
439         break;
440       case _Op_clone:
441         ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
442         __arg->_M_any->_M_manager = __any->_M_manager;
443         break;
444       case _Op_destroy:
445         __ptr->~_Tp();
446         break;
447       case _Op_xfer:
448         ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
449         __ptr->~_Tp();
450         __arg->_M_any->_M_manager = __any->_M_manager;
451         const_cast<any*>(__any)->_M_manager = nullptr;
452         break;
453       }
454     }
456   template<typename _Tp>
457     void
458     any::_Manager_external<_Tp>::
459     _S_manage(_Op __which, const any* __any, _Arg* __arg)
460     {
461       // The contained object is *_M_storage._M_ptr
462       auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
463       switch (__which)
464       {
465       case _Op_access:
466         __arg->_M_obj = const_cast<_Tp*>(__ptr);
467         break;
468       case _Op_get_type_info:
469 #if __cpp_rtti
470         __arg->_M_typeinfo = &typeid(_Tp);
471 #endif
472         break;
473       case _Op_clone:
474         __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
475         __arg->_M_any->_M_manager = __any->_M_manager;
476         break;
477       case _Op_destroy:
478         delete __ptr;
479         break;
480       case _Op_xfer:
481         __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr;
482         __arg->_M_any->_M_manager = __any->_M_manager;
483         const_cast<any*>(__any)->_M_manager = nullptr;
484         break;
485       }
486     }
488   // @} group any
489 _GLIBCXX_END_NAMESPACE_VERSION
490 } // namespace fundamentals_v1
491 } // namespace experimental
492 } // namespace std
494 #endif // C++14
496 #endif // _GLIBCXX_EXPERIMENTAL_ANY