libstdc++
any
Go to the documentation of this file.
00001 // <experimental/any> -*- C++ -*-
00002 
00003 // Copyright (C) 2014-2018 Free Software Foundation, Inc.
00004 //
00005 // This file is part of the GNU ISO C++ Library.  This library is free
00006 // software; you can redistribute it and/or modify it under the
00007 // terms of the GNU General Public License as published by the
00008 // Free Software Foundation; either version 3, or (at your option)
00009 // any later version.
00010 
00011 // This library is distributed in the hope that it will be useful,
00012 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00013 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014 // GNU General Public License for more details.
00015 
00016 // Under Section 7 of GPL version 3, you are granted additional
00017 // permissions described in the GCC Runtime Library Exception, version
00018 // 3.1, as published by the Free Software Foundation.
00019 
00020 // You should have received a copy of the GNU General Public License and
00021 // a copy of the GCC Runtime Library Exception along with this program;
00022 // see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
00023 // <http://www.gnu.org/licenses/>.
00024 
00025 /** @file experimental/any
00026  *  This is a TS C++ Library header.
00027  */
00028 
00029 #ifndef _GLIBCXX_EXPERIMENTAL_ANY
00030 #define _GLIBCXX_EXPERIMENTAL_ANY 1
00031 
00032 #pragma GCC system_header
00033 
00034 #if __cplusplus >= 201402L
00035 
00036 #include <typeinfo>
00037 #include <new>
00038 #include <utility>
00039 #include <type_traits>
00040 #include <experimental/bits/lfts_config.h>
00041 
00042 namespace std _GLIBCXX_VISIBILITY(default)
00043 {
00044 _GLIBCXX_BEGIN_NAMESPACE_VERSION
00045 
00046 namespace experimental
00047 {
00048 inline namespace fundamentals_v1
00049 {
00050   /**
00051    * @defgroup any Type-safe container of any type
00052    * @ingroup experimental
00053    *
00054    * A type-safe container for single values of value types, as
00055    * described in n3804 "Any Library Proposal (Revision 3)".
00056    *
00057    * @{
00058    */
00059 
00060 #define __cpp_lib_experimental_any 201411
00061 
00062   /**
00063    *  @brief Exception class thrown by a failed @c any_cast
00064    *  @ingroup exceptions
00065    */
00066   class bad_any_cast : public bad_cast
00067   {
00068   public:
00069     virtual const char* what() const noexcept { return "bad any_cast"; }
00070   };
00071 
00072   [[gnu::noreturn]] inline void __throw_bad_any_cast()
00073   {
00074 #if __cpp_exceptions
00075     throw bad_any_cast{};
00076 #else
00077     __builtin_abort();
00078 #endif
00079   }
00080 
00081   /**
00082    *  @brief A type-safe container of any type.
00083    * 
00084    *  An @c any object's state is either empty or it stores a contained object
00085    *  of CopyConstructible type.
00086    */
00087   class any
00088   {
00089     // Holds either pointer to a heap object or the contained object itself.
00090     union _Storage
00091     {
00092       // This constructor intentionally doesn't initialize anything.
00093       _Storage() = default;
00094 
00095       // Prevent trivial copies of this type, buffer might hold a non-POD.
00096       _Storage(const _Storage&) = delete;
00097       _Storage& operator=(const _Storage&) = delete;
00098 
00099       void* _M_ptr;
00100       aligned_storage<sizeof(_M_ptr), alignof(void*)>::type _M_buffer;
00101     };
00102 
00103     template<typename _Tp, typename _Safe = is_nothrow_move_constructible<_Tp>,
00104              bool _Fits = (sizeof(_Tp) <= sizeof(_Storage))
00105                           && (alignof(_Tp) <= alignof(_Storage))>
00106       using _Internal = std::integral_constant<bool, _Safe::value && _Fits>;
00107 
00108     template<typename _Tp>
00109       struct _Manager_internal; // uses small-object optimization
00110 
00111     template<typename _Tp>
00112       struct _Manager_external; // creates contained object on the heap
00113 
00114     template<typename _Tp>
00115       using _Manager = conditional_t<_Internal<_Tp>::value,
00116                                      _Manager_internal<_Tp>,
00117                                      _Manager_external<_Tp>>;
00118 
00119     template<typename _Tp, typename _Decayed = decay_t<_Tp>>
00120       using _Decay = enable_if_t<!is_same<_Decayed, any>::value, _Decayed>;
00121 
00122   public:
00123     // construct/destruct
00124 
00125     /// Default constructor, creates an empty object.
00126     any() noexcept : _M_manager(nullptr) { }
00127 
00128     /// Copy constructor, copies the state of @p __other
00129     any(const any& __other)
00130     {
00131       if (__other.empty())
00132         _M_manager = nullptr;
00133       else
00134         {
00135           _Arg __arg;
00136           __arg._M_any = this;
00137           __other._M_manager(_Op_clone, &__other, &__arg);
00138         }
00139     }
00140 
00141     /**
00142      * @brief Move constructor, transfer the state from @p __other
00143      *
00144      * @post @c __other.empty() (this postcondition is a GNU extension)
00145      */
00146     any(any&& __other) noexcept
00147     {
00148       if (__other.empty())
00149         _M_manager = nullptr;
00150       else
00151         {
00152           _Arg __arg;
00153           __arg._M_any = this;
00154           __other._M_manager(_Op_xfer, &__other, &__arg);
00155         }
00156     }
00157 
00158     /// Construct with a copy of @p __value as the contained object.
00159     template <typename _ValueType, typename _Tp = _Decay<_ValueType>,
00160               typename _Mgr = _Manager<_Tp>,
00161               typename enable_if<is_constructible<_Tp, _ValueType&&>::value,
00162                                  bool>::type = true>
00163       any(_ValueType&& __value)
00164       : _M_manager(&_Mgr::_S_manage)
00165       {
00166         _Mgr::_S_create(_M_storage, std::forward<_ValueType>(__value));
00167         static_assert(is_copy_constructible<_Tp>::value,
00168                       "The contained object must be CopyConstructible");
00169       }
00170 
00171     /// Construct with a copy of @p __value as the contained object.
00172     template <typename _ValueType, typename _Tp = _Decay<_ValueType>,
00173               typename _Mgr = _Manager<_Tp>,
00174               typename enable_if<!is_constructible<_Tp, _ValueType&&>::value,
00175                                  bool>::type = false>
00176       any(_ValueType&& __value)
00177       : _M_manager(&_Mgr::_S_manage)
00178       {
00179         _Mgr::_S_create(_M_storage, __value);
00180         static_assert(is_copy_constructible<_Tp>::value,
00181                       "The contained object must be CopyConstructible");
00182       }
00183 
00184     /// Destructor, calls @c clear()
00185     ~any() { clear(); }
00186 
00187     // assignments
00188 
00189     /// Copy the state of another object.
00190     any& operator=(const any& __rhs)
00191     {
00192       *this = any(__rhs);
00193       return *this;
00194     }
00195 
00196     /**
00197      * @brief Move assignment operator
00198      *
00199      * @post @c __rhs.empty() (not guaranteed for other implementations)
00200      */
00201     any& operator=(any&& __rhs) noexcept
00202     {
00203       if (__rhs.empty())
00204         clear();
00205       else if (this != &__rhs)
00206         {
00207           clear();
00208           _Arg __arg;
00209           __arg._M_any = this;
00210           __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
00211         }
00212       return *this;
00213     }
00214 
00215     /// Store a copy of @p __rhs as the contained object.
00216     template<typename _ValueType>
00217       enable_if_t<!is_same<any, decay_t<_ValueType>>::value, any&>
00218       operator=(_ValueType&& __rhs)
00219       {
00220         *this = any(std::forward<_ValueType>(__rhs));
00221         return *this;
00222       }
00223 
00224     // modifiers
00225 
00226     /// If not empty, destroy the contained object.
00227     void clear() noexcept
00228     {
00229       if (!empty())
00230       {
00231         _M_manager(_Op_destroy, this, nullptr);
00232         _M_manager = nullptr;
00233       }
00234     }
00235 
00236     /// Exchange state with another object.
00237     void swap(any& __rhs) noexcept
00238     {
00239       if (empty() && __rhs.empty())
00240         return;
00241 
00242       if (!empty() && !__rhs.empty())
00243         {
00244           if (this == &__rhs)
00245             return;
00246 
00247           any __tmp;
00248           _Arg __arg;
00249           __arg._M_any = &__tmp;
00250           __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
00251           __arg._M_any = &__rhs;
00252           _M_manager(_Op_xfer, this, &__arg);
00253           __arg._M_any = this;
00254           __tmp._M_manager(_Op_xfer, &__tmp, &__arg);
00255         }
00256       else
00257         {
00258           any* __empty = empty() ? this : &__rhs;
00259           any* __full = empty() ? &__rhs : this;
00260           _Arg __arg;
00261           __arg._M_any = __empty;
00262           __full->_M_manager(_Op_xfer, __full, &__arg);
00263         }
00264     }
00265 
00266     // observers
00267 
00268     /// Reports whether there is a contained object or not.
00269     bool empty() const noexcept { return _M_manager == nullptr; }
00270 
00271 #if __cpp_rtti
00272     /// The @c typeid of the contained object, or @c typeid(void) if empty.
00273     const type_info& type() const noexcept
00274     {
00275       if (empty())
00276         return typeid(void);
00277       _Arg __arg;
00278       _M_manager(_Op_get_type_info, this, &__arg);
00279       return *__arg._M_typeinfo;
00280     }
00281 #endif
00282 
00283     template<typename _Tp>
00284       static constexpr bool __is_valid_cast()
00285       { return __or_<is_reference<_Tp>, is_copy_constructible<_Tp>>::value; }
00286 
00287   private:
00288     enum _Op {
00289         _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer
00290     };
00291 
00292     union _Arg
00293     {
00294         void* _M_obj;
00295         const std::type_info* _M_typeinfo;
00296         any* _M_any;
00297     };
00298 
00299     void (*_M_manager)(_Op, const any*, _Arg*);
00300     _Storage _M_storage;
00301 
00302     template<typename _Tp>
00303       friend void* __any_caster(const any* __any);
00304 
00305     // Manage in-place contained object.
00306     template<typename _Tp>
00307       struct _Manager_internal
00308       {
00309         static void
00310         _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
00311 
00312         template<typename _Up>
00313           static void
00314           _S_create(_Storage& __storage, _Up&& __value)
00315           {
00316             void* __addr = &__storage._M_buffer;
00317             ::new (__addr) _Tp(std::forward<_Up>(__value));
00318           }
00319       };
00320 
00321     // Manage external contained object.
00322     template<typename _Tp>
00323       struct _Manager_external
00324       {
00325         static void
00326         _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
00327 
00328         template<typename _Up>
00329           static void
00330           _S_create(_Storage& __storage, _Up&& __value)
00331           {
00332             __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
00333           }
00334       };
00335   };
00336 
00337   /// Exchange the states of two @c any objects.
00338   inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
00339 
00340   /**
00341    * @brief Access the contained object.
00342    *
00343    * @tparam  _ValueType  A const-reference or CopyConstructible type.
00344    * @param   __any       The object to access.
00345    * @return  The contained object.
00346    * @throw   bad_any_cast If <code>
00347    *          __any.type() != typeid(remove_reference_t<_ValueType>)
00348    *          </code>
00349    */
00350   template<typename _ValueType>
00351     inline _ValueType any_cast(const any& __any)
00352     {
00353       static_assert(any::__is_valid_cast<_ValueType>(),
00354           "Template argument must be a reference or CopyConstructible type");
00355       auto __p = any_cast<add_const_t<remove_reference_t<_ValueType>>>(&__any);
00356       if (__p)
00357         return *__p;
00358       __throw_bad_any_cast();
00359     }
00360 
00361   /**
00362    * @brief Access the contained object.
00363    *
00364    * @tparam  _ValueType  A reference or CopyConstructible type.
00365    * @param   __any       The object to access.
00366    * @return  The contained object.
00367    * @throw   bad_any_cast If <code>
00368    *          __any.type() != typeid(remove_reference_t<_ValueType>)
00369    *          </code>
00370    *
00371    * @{
00372    */
00373   template<typename _ValueType>
00374     inline _ValueType any_cast(any& __any)
00375     {
00376       static_assert(any::__is_valid_cast<_ValueType>(),
00377           "Template argument must be a reference or CopyConstructible type");
00378       auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
00379       if (__p)
00380         return *__p;
00381       __throw_bad_any_cast();
00382     }
00383 
00384   template<typename _ValueType,
00385            typename enable_if<!is_move_constructible<_ValueType>::value
00386                               || is_lvalue_reference<_ValueType>::value,
00387                               bool>::type = true>
00388     inline _ValueType any_cast(any&& __any)
00389     {
00390       static_assert(any::__is_valid_cast<_ValueType>(),
00391           "Template argument must be a reference or CopyConstructible type");
00392       auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
00393       if (__p)
00394         return *__p;
00395       __throw_bad_any_cast();
00396     }
00397 
00398   template<typename _ValueType,
00399            typename enable_if<is_move_constructible<_ValueType>::value
00400                               && !is_lvalue_reference<_ValueType>::value,
00401                               bool>::type = false>
00402     inline _ValueType any_cast(any&& __any)
00403     {
00404       static_assert(any::__is_valid_cast<_ValueType>(),
00405           "Template argument must be a reference or CopyConstructible type");
00406       auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
00407       if (__p)
00408         return std::move(*__p);
00409       __throw_bad_any_cast();
00410     }
00411   // @}
00412 
00413   template<typename _Tp>
00414     void* __any_caster(const any* __any)
00415     {
00416       struct _None { };
00417       using _Up = decay_t<_Tp>;
00418       using _Vp = conditional_t<is_copy_constructible<_Up>::value, _Up, _None>;
00419       if (__any->_M_manager != &any::_Manager<_Vp>::_S_manage)
00420         return nullptr;
00421       any::_Arg __arg;
00422       __any->_M_manager(any::_Op_access, __any, &__arg);
00423       return __arg._M_obj;
00424     }
00425 
00426   /**
00427    * @brief Access the contained object.
00428    *
00429    * @tparam  _ValueType  The type of the contained object.
00430    * @param   __any       A pointer to the object to access.
00431    * @return  The address of the contained object if <code>
00432    *          __any != nullptr && __any.type() == typeid(_ValueType)
00433    *          </code>, otherwise a null pointer.
00434    *
00435    * @{
00436    */
00437   template<typename _ValueType>
00438     inline const _ValueType* any_cast(const any* __any) noexcept
00439     {
00440       if (__any)
00441         return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
00442       return nullptr;
00443     }
00444 
00445   template<typename _ValueType>
00446     inline _ValueType* any_cast(any* __any) noexcept
00447     {
00448       if (__any)
00449         return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
00450       return nullptr;
00451     }
00452   // @}
00453 
00454   template<typename _Tp>
00455     void
00456     any::_Manager_internal<_Tp>::
00457     _S_manage(_Op __which, const any* __any, _Arg* __arg)
00458     {
00459       // The contained object is in _M_storage._M_buffer
00460       auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
00461       switch (__which)
00462       {
00463       case _Op_access:
00464         __arg->_M_obj = const_cast<_Tp*>(__ptr);
00465         break;
00466       case _Op_get_type_info:
00467 #if __cpp_rtti
00468         __arg->_M_typeinfo = &typeid(_Tp);
00469 #endif
00470         break;
00471       case _Op_clone:
00472         ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
00473         __arg->_M_any->_M_manager = __any->_M_manager;
00474         break;
00475       case _Op_destroy:
00476         __ptr->~_Tp();
00477         break;
00478       case _Op_xfer:
00479         ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp
00480           (std::move(*const_cast<_Tp*>(__ptr)));
00481         __ptr->~_Tp();
00482         __arg->_M_any->_M_manager = __any->_M_manager;
00483         const_cast<any*>(__any)->_M_manager = nullptr;
00484         break;
00485       }
00486     }
00487 
00488   template<typename _Tp>
00489     void
00490     any::_Manager_external<_Tp>::
00491     _S_manage(_Op __which, const any* __any, _Arg* __arg)
00492     {
00493       // The contained object is *_M_storage._M_ptr
00494       auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
00495       switch (__which)
00496       {
00497       case _Op_access:
00498         __arg->_M_obj = const_cast<_Tp*>(__ptr);
00499         break;
00500       case _Op_get_type_info:
00501 #if __cpp_rtti
00502         __arg->_M_typeinfo = &typeid(_Tp);
00503 #endif
00504         break;
00505       case _Op_clone:
00506         __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
00507         __arg->_M_any->_M_manager = __any->_M_manager;
00508         break;
00509       case _Op_destroy:
00510         delete __ptr;
00511         break;
00512       case _Op_xfer:
00513         __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr;
00514         __arg->_M_any->_M_manager = __any->_M_manager;
00515         const_cast<any*>(__any)->_M_manager = nullptr;
00516         break;
00517       }
00518     }
00519 
00520   // @} group any
00521 } // namespace fundamentals_v1
00522 } // namespace experimental
00523 
00524 _GLIBCXX_END_NAMESPACE_VERSION
00525 } // namespace std
00526 
00527 #endif // C++14
00528 
00529 #endif // _GLIBCXX_EXPERIMENTAL_ANY