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