1// <experimental/any> -*- C++ -*-
2
3// Copyright (C) 2014-2018 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.
10
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.
15
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.
19
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/>.
24
25/** @file experimental/any
26 *  This is a TS C++ Library header.
27 */
28
29#ifndef _GLIBCXX_EXPERIMENTAL_ANY
30#define _GLIBCXX_EXPERIMENTAL_ANY 1
31
32#pragma GCC system_header
33
34#if __cplusplus >= 201402L
35
36#include <typeinfo>
37#include <new>
38#include <utility>
39#include <type_traits>
40#include <experimental/bits/lfts_config.h>
41
42namespace std _GLIBCXX_VISIBILITY(default)
43{
44_GLIBCXX_BEGIN_NAMESPACE_VERSION
45
46namespace experimental
47{
48inline namespace fundamentals_v1
49{
50  /**
51   * @defgroup any Type-safe container of any type
52   * @ingroup experimental
53   *
54   * A type-safe container for single values of value types, as
55   * described in n3804 "Any Library Proposal (Revision 3)".
56   *
57   * @{
58   */
59
60#define __cpp_lib_experimental_any 201411
61
62  /**
63   *  @brief Exception class thrown by a failed @c any_cast
64   *  @ingroup exceptions
65   */
66  class bad_any_cast : public bad_cast
67  {
68  public:
69    virtual const char* what() const noexcept { return "bad any_cast"; }
70  };
71
72  [[gnu::noreturn]] inline void __throw_bad_any_cast()
73  {
74#if __cpp_exceptions
75    throw bad_any_cast{};
76#else
77    __builtin_abort();
78#endif
79  }
80
81  /**
82   *  @brief A type-safe container of any type.
83   *
84   *  An @c any object's state is either empty or it stores a contained object
85   *  of CopyConstructible type.
86   */
87  class any
88  {
89    // Holds either pointer to a heap object or the contained object itself.
90    union _Storage
91    {
92      // This constructor intentionally doesn't initialize anything.
93      _Storage() = default;
94
95      // Prevent trivial copies of this type, buffer might hold a non-POD.
96      _Storage(const _Storage&) = delete;
97      _Storage& operator=(const _Storage&) = delete;
98
99      void* _M_ptr;
100      aligned_storage<sizeof(_M_ptr), alignof(void*)>::type _M_buffer;
101    };
102
103    template<typename _Tp, typename _Safe = is_nothrow_move_constructible<_Tp>,
104	     bool _Fits = (sizeof(_Tp) <= sizeof(_Storage))
105			  && (alignof(_Tp) <= alignof(_Storage))>
106      using _Internal = std::integral_constant<bool, _Safe::value && _Fits>;
107
108    template<typename _Tp>
109      struct _Manager_internal; // uses small-object optimization
110
111    template<typename _Tp>
112      struct _Manager_external; // creates contained object on the heap
113
114    template<typename _Tp>
115      using _Manager = conditional_t<_Internal<_Tp>::value,
116				     _Manager_internal<_Tp>,
117				     _Manager_external<_Tp>>;
118
119    template<typename _Tp, typename _Decayed = decay_t<_Tp>>
120      using _Decay = enable_if_t<!is_same<_Decayed, any>::value, _Decayed>;
121
122  public:
123    // construct/destruct
124
125    /// Default constructor, creates an empty object.
126    any() noexcept : _M_manager(nullptr) { }
127
128    /// Copy constructor, copies the state of @p __other
129    any(const any& __other)
130    {
131      if (__other.empty())
132	_M_manager = nullptr;
133      else
134	{
135	  _Arg __arg;
136	  __arg._M_any = this;
137	  __other._M_manager(_Op_clone, &__other, &__arg);
138	}
139    }
140
141    /**
142     * @brief Move constructor, transfer the state from @p __other
143     *
144     * @post @c __other.empty() (this postcondition is a GNU extension)
145     */
146    any(any&& __other) noexcept
147    {
148      if (__other.empty())
149	_M_manager = nullptr;
150      else
151	{
152	  _Arg __arg;
153	  __arg._M_any = this;
154	  __other._M_manager(_Op_xfer, &__other, &__arg);
155	}
156    }
157
158    /// Construct with a copy of @p __value as the contained object.
159    template <typename _ValueType, typename _Tp = _Decay<_ValueType>,
160	      typename _Mgr = _Manager<_Tp>,
161              typename enable_if<is_constructible<_Tp, _ValueType&&>::value,
162                                 bool>::type = true>
163      any(_ValueType&& __value)
164      : _M_manager(&_Mgr::_S_manage)
165      {
166        _Mgr::_S_create(_M_storage, std::forward<_ValueType>(__value));
167	static_assert(is_copy_constructible<_Tp>::value,
168		      "The contained object must be CopyConstructible");
169      }
170
171    /// Construct with a copy of @p __value as the contained object.
172    template <typename _ValueType, typename _Tp = _Decay<_ValueType>,
173	      typename _Mgr = _Manager<_Tp>,
174              typename enable_if<!is_constructible<_Tp, _ValueType&&>::value,
175                                 bool>::type = false>
176      any(_ValueType&& __value)
177      : _M_manager(&_Mgr::_S_manage)
178      {
179        _Mgr::_S_create(_M_storage, __value);
180	static_assert(is_copy_constructible<_Tp>::value,
181		      "The contained object must be CopyConstructible");
182      }
183
184    /// Destructor, calls @c clear()
185    ~any() { clear(); }
186
187    // assignments
188
189    /// Copy the state of another object.
190    any& operator=(const any& __rhs)
191    {
192      *this = any(__rhs);
193      return *this;
194    }
195
196    /**
197     * @brief Move assignment operator
198     *
199     * @post @c __rhs.empty() (not guaranteed for other implementations)
200     */
201    any& operator=(any&& __rhs) noexcept
202    {
203      if (__rhs.empty())
204	clear();
205      else if (this != &__rhs)
206	{
207	  clear();
208	  _Arg __arg;
209	  __arg._M_any = this;
210	  __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
211	}
212      return *this;
213    }
214
215    /// Store a copy of @p __rhs as the contained object.
216    template<typename _ValueType>
217      enable_if_t<!is_same<any, decay_t<_ValueType>>::value, any&>
218      operator=(_ValueType&& __rhs)
219      {
220	*this = any(std::forward<_ValueType>(__rhs));
221	return *this;
222      }
223
224    // modifiers
225
226    /// If not empty, destroy the contained object.
227    void clear() noexcept
228    {
229      if (!empty())
230      {
231	_M_manager(_Op_destroy, this, nullptr);
232	_M_manager = nullptr;
233      }
234    }
235
236    /// Exchange state with another object.
237    void swap(any& __rhs) noexcept
238    {
239      if (empty() && __rhs.empty())
240	return;
241
242      if (!empty() && !__rhs.empty())
243	{
244	  if (this == &__rhs)
245	    return;
246
247	  any __tmp;
248	  _Arg __arg;
249	  __arg._M_any = &__tmp;
250	  __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
251	  __arg._M_any = &__rhs;
252	  _M_manager(_Op_xfer, this, &__arg);
253	  __arg._M_any = this;
254	  __tmp._M_manager(_Op_xfer, &__tmp, &__arg);
255	}
256      else
257	{
258	  any* __empty = empty() ? this : &__rhs;
259	  any* __full = empty() ? &__rhs : this;
260	  _Arg __arg;
261	  __arg._M_any = __empty;
262	  __full->_M_manager(_Op_xfer, __full, &__arg);
263	}
264    }
265
266    // observers
267
268    /// Reports whether there is a contained object or not.
269    bool empty() const noexcept { return _M_manager == nullptr; }
270
271#if __cpp_rtti
272    /// The @c typeid of the contained object, or @c typeid(void) if empty.
273    const type_info& type() const noexcept
274    {
275      if (empty())
276	return typeid(void);
277      _Arg __arg;
278      _M_manager(_Op_get_type_info, this, &__arg);
279      return *__arg._M_typeinfo;
280    }
281#endif
282
283    template<typename _Tp>
284      static constexpr bool __is_valid_cast()
285      { return __or_<is_reference<_Tp>, is_copy_constructible<_Tp>>::value; }
286
287  private:
288    enum _Op {
289	_Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer
290    };
291
292    union _Arg
293    {
294	void* _M_obj;
295	const std::type_info* _M_typeinfo;
296	any* _M_any;
297    };
298
299    void (*_M_manager)(_Op, const any*, _Arg*);
300    _Storage _M_storage;
301
302    template<typename _Tp>
303      friend enable_if_t<is_object<_Tp>::value, void*>
304      __any_caster(const any* __any);
305
306    // Manage in-place contained object.
307    template<typename _Tp>
308      struct _Manager_internal
309      {
310	static void
311	_S_manage(_Op __which, const any* __anyp, _Arg* __arg);
312
313	template<typename _Up>
314	  static void
315	  _S_create(_Storage& __storage, _Up&& __value)
316	  {
317	    void* __addr = &__storage._M_buffer;
318	    ::new (__addr) _Tp(std::forward<_Up>(__value));
319	  }
320      };
321
322    // Manage external contained object.
323    template<typename _Tp>
324      struct _Manager_external
325      {
326	static void
327	_S_manage(_Op __which, const any* __anyp, _Arg* __arg);
328
329	template<typename _Up>
330	  static void
331	  _S_create(_Storage& __storage, _Up&& __value)
332	  {
333	    __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
334	  }
335      };
336  };
337
338  /// Exchange the states of two @c any objects.
339  inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
340
341  /**
342   * @brief Access the contained object.
343   *
344   * @tparam  _ValueType  A const-reference or CopyConstructible type.
345   * @param   __any       The object to access.
346   * @return  The contained object.
347   * @throw   bad_any_cast If <code>
348   *          __any.type() != typeid(remove_reference_t<_ValueType>)
349   *          </code>
350   */
351  template<typename _ValueType>
352    inline _ValueType any_cast(const any& __any)
353    {
354      static_assert(any::__is_valid_cast<_ValueType>(),
355	  "Template argument must be a reference or CopyConstructible type");
356      auto __p = any_cast<add_const_t<remove_reference_t<_ValueType>>>(&__any);
357      if (__p)
358	return *__p;
359      __throw_bad_any_cast();
360    }
361
362  /**
363   * @brief Access the contained object.
364   *
365   * @tparam  _ValueType  A reference or CopyConstructible type.
366   * @param   __any       The object to access.
367   * @return  The contained object.
368   * @throw   bad_any_cast If <code>
369   *          __any.type() != typeid(remove_reference_t<_ValueType>)
370   *          </code>
371   *
372   * @{
373   */
374  template<typename _ValueType>
375    inline _ValueType any_cast(any& __any)
376    {
377      static_assert(any::__is_valid_cast<_ValueType>(),
378	  "Template argument must be a reference or CopyConstructible type");
379      auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
380      if (__p)
381	return *__p;
382      __throw_bad_any_cast();
383    }
384
385  template<typename _ValueType,
386           typename enable_if<!is_move_constructible<_ValueType>::value
387                              || is_lvalue_reference<_ValueType>::value,
388                              bool>::type = true>
389    inline _ValueType any_cast(any&& __any)
390    {
391      static_assert(any::__is_valid_cast<_ValueType>(),
392	  "Template argument must be a reference or CopyConstructible type");
393      auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
394      if (__p)
395	return *__p;
396      __throw_bad_any_cast();
397    }
398
399  template<typename _ValueType,
400           typename enable_if<is_move_constructible<_ValueType>::value
401                              && !is_lvalue_reference<_ValueType>::value,
402                              bool>::type = false>
403    inline _ValueType any_cast(any&& __any)
404    {
405      static_assert(any::__is_valid_cast<_ValueType>(),
406	  "Template argument must be a reference or CopyConstructible type");
407      auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
408      if (__p)
409	return std::move(*__p);
410      __throw_bad_any_cast();
411    }
412  // @}
413
414  /// @cond undocumented
415  template<typename _Tp>
416    enable_if_t<is_object<_Tp>::value, void*>
417    __any_caster(const any* __any)
418    {
419      // any_cast<T> returns non-null if __any->type() == typeid(T) and
420      // typeid(T) ignores cv-qualifiers so remove them:
421      using _Up = remove_cv_t<_Tp>;
422      // The contained value has a decayed type, so if decay_t<U> is not U,
423      // then it's not possible to have a contained value of type U.
424      using __does_not_decay = is_same<decay_t<_Up>, _Up>;
425      // Only copy constructible types can be used for contained values.
426      using __is_copyable = is_copy_constructible<_Up>;
427      // If the type _Tp could never be stored in an any we don't want to
428      // instantiate _Manager<_Tp>, so use _Manager<any::_Op> instead, which
429      // is explicitly specialized and has a no-op _S_manage function.
430      using _Vp = conditional_t<__and_<__does_not_decay, __is_copyable>::value,
431				_Up, any::_Op>;
432      // First try comparing function addresses, which works without RTTI
433      if (__any->_M_manager == &any::_Manager<_Vp>::_S_manage
434#if __cpp_rtti
435	  || __any->type() == typeid(_Tp)
436#endif
437	  )
438	{
439	  any::_Arg __arg;
440	  __any->_M_manager(any::_Op_access, __any, &__arg);
441	  return __arg._M_obj;
442	}
443      return nullptr;
444    }
445
446  // This overload exists so that std::any_cast<void(*)()>(a) is well-formed.
447  template<typename _Tp>
448    enable_if_t<!is_object<_Tp>::value, _Tp*>
449    __any_caster(const any*) noexcept
450    { return nullptr; }
451  /// @endcond
452
453  /**
454   * @brief Access the contained object.
455   *
456   * @tparam  _ValueType  The type of the contained object.
457   * @param   __any       A pointer to the object to access.
458   * @return  The address of the contained object if <code>
459   *          __any != nullptr && __any.type() == typeid(_ValueType)
460   *          </code>, otherwise a null pointer.
461   *
462   * @{
463   */
464  template<typename _ValueType>
465    inline const _ValueType* any_cast(const any* __any) noexcept
466    {
467      if (__any)
468	return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
469      return nullptr;
470    }
471
472  template<typename _ValueType>
473    inline _ValueType* any_cast(any* __any) noexcept
474    {
475      if (__any)
476	return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
477      return nullptr;
478    }
479  // @}
480
481  template<typename _Tp>
482    void
483    any::_Manager_internal<_Tp>::
484    _S_manage(_Op __which, const any* __any, _Arg* __arg)
485    {
486      // The contained object is in _M_storage._M_buffer
487      auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
488      switch (__which)
489      {
490      case _Op_access:
491	__arg->_M_obj = const_cast<_Tp*>(__ptr);
492	break;
493      case _Op_get_type_info:
494#if __cpp_rtti
495	__arg->_M_typeinfo = &typeid(_Tp);
496#endif
497	break;
498      case _Op_clone:
499	::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
500	__arg->_M_any->_M_manager = __any->_M_manager;
501	break;
502      case _Op_destroy:
503	__ptr->~_Tp();
504	break;
505      case _Op_xfer:
506	::new(&__arg->_M_any->_M_storage._M_buffer) _Tp
507	  (std::move(*const_cast<_Tp*>(__ptr)));
508	__ptr->~_Tp();
509	__arg->_M_any->_M_manager = __any->_M_manager;
510	const_cast<any*>(__any)->_M_manager = nullptr;
511	break;
512      }
513    }
514
515  template<typename _Tp>
516    void
517    any::_Manager_external<_Tp>::
518    _S_manage(_Op __which, const any* __any, _Arg* __arg)
519    {
520      // The contained object is *_M_storage._M_ptr
521      auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
522      switch (__which)
523      {
524      case _Op_access:
525	__arg->_M_obj = const_cast<_Tp*>(__ptr);
526	break;
527      case _Op_get_type_info:
528#if __cpp_rtti
529	__arg->_M_typeinfo = &typeid(_Tp);
530#endif
531	break;
532      case _Op_clone:
533	__arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
534	__arg->_M_any->_M_manager = __any->_M_manager;
535	break;
536      case _Op_destroy:
537	delete __ptr;
538	break;
539      case _Op_xfer:
540	__arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr;
541	__arg->_M_any->_M_manager = __any->_M_manager;
542	const_cast<any*>(__any)->_M_manager = nullptr;
543	break;
544      }
545    }
546
547  // Dummy specialization used by __any_caster.
548  template<>
549    struct any::_Manager_internal<any::_Op>
550    {
551      static void
552      _S_manage(_Op, const any*, _Arg*) { }
553    };
554
555  // @} group any
556} // namespace fundamentals_v1
557} // namespace experimental
558
559_GLIBCXX_END_NAMESPACE_VERSION
560} // namespace std
561
562#endif // C++14
563
564#endif // _GLIBCXX_EXPERIMENTAL_ANY
565