libstdc++
any
Go to the documentation of this file.
00001 // <experimental/any> -*- C++ -*-
00002 
00003 // Copyright (C) 2014-2019 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     _GLIBCXX_NODISCARD 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 enable_if_t<is_object<_Tp>::value, void*>
00304       __any_caster(const any* __any);
00305 
00306     // Manage in-place contained object.
00307     template<typename _Tp>
00308       struct _Manager_internal
00309       {
00310         static void
00311         _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
00312 
00313         template<typename _Up>
00314           static void
00315           _S_create(_Storage& __storage, _Up&& __value)
00316           {
00317             void* __addr = &__storage._M_buffer;
00318             ::new (__addr) _Tp(std::forward<_Up>(__value));
00319           }
00320       };
00321 
00322     // Manage external contained object.
00323     template<typename _Tp>
00324       struct _Manager_external
00325       {
00326         static void
00327         _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
00328 
00329         template<typename _Up>
00330           static void
00331           _S_create(_Storage& __storage, _Up&& __value)
00332           {
00333             __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
00334           }
00335       };
00336   };
00337 
00338   /// Exchange the states of two @c any objects.
00339   inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
00340 
00341   /**
00342    * @brief Access the contained object.
00343    *
00344    * @tparam  _ValueType  A const-reference or CopyConstructible type.
00345    * @param   __any       The object to access.
00346    * @return  The contained object.
00347    * @throw   bad_any_cast If <code>
00348    *          __any.type() != typeid(remove_reference_t<_ValueType>)
00349    *          </code>
00350    */
00351   template<typename _ValueType>
00352     inline _ValueType any_cast(const any& __any)
00353     {
00354       static_assert(any::__is_valid_cast<_ValueType>(),
00355           "Template argument must be a reference or CopyConstructible type");
00356       auto __p = any_cast<add_const_t<remove_reference_t<_ValueType>>>(&__any);
00357       if (__p)
00358         return *__p;
00359       __throw_bad_any_cast();
00360     }
00361 
00362   /**
00363    * @brief Access the contained object.
00364    *
00365    * @tparam  _ValueType  A reference or CopyConstructible type.
00366    * @param   __any       The object to access.
00367    * @return  The contained object.
00368    * @throw   bad_any_cast If <code>
00369    *          __any.type() != typeid(remove_reference_t<_ValueType>)
00370    *          </code>
00371    *
00372    * @{
00373    */
00374   template<typename _ValueType>
00375     inline _ValueType any_cast(any& __any)
00376     {
00377       static_assert(any::__is_valid_cast<_ValueType>(),
00378           "Template argument must be a reference or CopyConstructible type");
00379       auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
00380       if (__p)
00381         return *__p;
00382       __throw_bad_any_cast();
00383     }
00384 
00385   template<typename _ValueType,
00386            typename enable_if<!is_move_constructible<_ValueType>::value
00387                               || is_lvalue_reference<_ValueType>::value,
00388                               bool>::type = true>
00389     inline _ValueType any_cast(any&& __any)
00390     {
00391       static_assert(any::__is_valid_cast<_ValueType>(),
00392           "Template argument must be a reference or CopyConstructible type");
00393       auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
00394       if (__p)
00395         return *__p;
00396       __throw_bad_any_cast();
00397     }
00398 
00399   template<typename _ValueType,
00400            typename enable_if<is_move_constructible<_ValueType>::value
00401                               && !is_lvalue_reference<_ValueType>::value,
00402                               bool>::type = false>
00403     inline _ValueType any_cast(any&& __any)
00404     {
00405       static_assert(any::__is_valid_cast<_ValueType>(),
00406           "Template argument must be a reference or CopyConstructible type");
00407       auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
00408       if (__p)
00409         return std::move(*__p);
00410       __throw_bad_any_cast();
00411     }
00412   // @}
00413 
00414   /// @cond undocumented
00415   template<typename _Tp>
00416     enable_if_t<is_object<_Tp>::value, void*>
00417     __any_caster(const any* __any)
00418     {
00419       // any_cast<T> returns non-null if __any->type() == typeid(T) and
00420       // typeid(T) ignores cv-qualifiers so remove them:
00421       using _Up = remove_cv_t<_Tp>;
00422       // The contained value has a decayed type, so if decay_t<U> is not U,
00423       // then it's not possible to have a contained value of type U.
00424       using __does_not_decay = is_same<decay_t<_Up>, _Up>;
00425       // Only copy constructible types can be used for contained values.
00426       using __is_copyable = is_copy_constructible<_Up>;
00427       // If the type _Tp could never be stored in an any we don't want to
00428       // instantiate _Manager<_Tp>, so use _Manager<any::_Op> instead, which
00429       // is explicitly specialized and has a no-op _S_manage function.
00430       using _Vp = conditional_t<__and_<__does_not_decay, __is_copyable>::value,
00431                                 _Up, any::_Op>;
00432       // First try comparing function addresses, which works without RTTI
00433       if (__any->_M_manager == &any::_Manager<_Vp>::_S_manage
00434 #if __cpp_rtti
00435           || __any->type() == typeid(_Tp)
00436 #endif
00437           )
00438         {
00439           any::_Arg __arg;
00440           __any->_M_manager(any::_Op_access, __any, &__arg);
00441           return __arg._M_obj;
00442         }
00443       return nullptr;
00444     }
00445 
00446   // This overload exists so that std::any_cast<void(*)()>(a) is well-formed.
00447   template<typename _Tp>
00448     enable_if_t<!is_object<_Tp>::value, _Tp*>
00449     __any_caster(const any*) noexcept
00450     { return nullptr; }
00451   /// @endcond
00452 
00453   /**
00454    * @brief Access the contained object.
00455    *
00456    * @tparam  _ValueType  The type of the contained object.
00457    * @param   __any       A pointer to the object to access.
00458    * @return  The address of the contained object if <code>
00459    *          __any != nullptr && __any.type() == typeid(_ValueType)
00460    *          </code>, otherwise a null pointer.
00461    *
00462    * @{
00463    */
00464   template<typename _ValueType>
00465     inline const _ValueType* any_cast(const any* __any) noexcept
00466     {
00467       if (__any)
00468         return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
00469       return nullptr;
00470     }
00471 
00472   template<typename _ValueType>
00473     inline _ValueType* any_cast(any* __any) noexcept
00474     {
00475       if (__any)
00476         return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
00477       return nullptr;
00478     }
00479   // @}
00480 
00481   template<typename _Tp>
00482     void
00483     any::_Manager_internal<_Tp>::
00484     _S_manage(_Op __which, const any* __any, _Arg* __arg)
00485     {
00486       // The contained object is in _M_storage._M_buffer
00487       auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
00488       switch (__which)
00489       {
00490       case _Op_access:
00491         __arg->_M_obj = const_cast<_Tp*>(__ptr);
00492         break;
00493       case _Op_get_type_info:
00494 #if __cpp_rtti
00495         __arg->_M_typeinfo = &typeid(_Tp);
00496 #endif
00497         break;
00498       case _Op_clone:
00499         ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
00500         __arg->_M_any->_M_manager = __any->_M_manager;
00501         break;
00502       case _Op_destroy:
00503         __ptr->~_Tp();
00504         break;
00505       case _Op_xfer:
00506         ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp
00507           (std::move(*const_cast<_Tp*>(__ptr)));
00508         __ptr->~_Tp();
00509         __arg->_M_any->_M_manager = __any->_M_manager;
00510         const_cast<any*>(__any)->_M_manager = nullptr;
00511         break;
00512       }
00513     }
00514 
00515   template<typename _Tp>
00516     void
00517     any::_Manager_external<_Tp>::
00518     _S_manage(_Op __which, const any* __any, _Arg* __arg)
00519     {
00520       // The contained object is *_M_storage._M_ptr
00521       auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
00522       switch (__which)
00523       {
00524       case _Op_access:
00525         __arg->_M_obj = const_cast<_Tp*>(__ptr);
00526         break;
00527       case _Op_get_type_info:
00528 #if __cpp_rtti
00529         __arg->_M_typeinfo = &typeid(_Tp);
00530 #endif
00531         break;
00532       case _Op_clone:
00533         __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
00534         __arg->_M_any->_M_manager = __any->_M_manager;
00535         break;
00536       case _Op_destroy:
00537         delete __ptr;
00538         break;
00539       case _Op_xfer:
00540         __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr;
00541         __arg->_M_any->_M_manager = __any->_M_manager;
00542         const_cast<any*>(__any)->_M_manager = nullptr;
00543         break;
00544       }
00545     }
00546 
00547   // Dummy specialization used by __any_caster.
00548   template<>
00549     struct any::_Manager_internal<any::_Op>
00550     {
00551       static void
00552       _S_manage(_Op, const any*, _Arg*) { }
00553     };
00554 
00555   // @} group any
00556 } // namespace fundamentals_v1
00557 } // namespace experimental
00558 
00559 _GLIBCXX_END_NAMESPACE_VERSION
00560 } // namespace std
00561 
00562 #endif // C++14
00563 
00564 #endif // _GLIBCXX_EXPERIMENTAL_ANY