any.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2017 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. #ifndef REALM_UTIL_ANY_HPP
  19. #define REALM_UTIL_ANY_HPP
  20. #include <any>
  21. namespace realm::util {
  22. using Any = std::any;
  23. // We can't use std::any_cast directly because the versions which throw on error
  24. // have a deployment target of iOS 11. Once we bump our deployment target to
  25. // that we should delete this.
  26. template <class T>
  27. T any_cast(Any const& v)
  28. {
  29. using U = std::remove_cv_t<std::remove_reference_t<T>>;
  30. static_assert(std::is_constructible_v<T, U const&>,
  31. "T must be a const lvalue reference or a CopyConstructible type");
  32. if (auto ptr = std::any_cast<std::add_const_t<U>>(&v))
  33. return static_cast<T>(*ptr);
  34. throw std::bad_cast();
  35. }
  36. template <class T>
  37. T any_cast(Any& v)
  38. {
  39. using U = std::remove_cv_t<std::remove_reference_t<T>>;
  40. static_assert(std::is_constructible_v<T, U&>, "T must be a lvalue reference or a CopyConstructible type");
  41. if (auto ptr = std::any_cast<U>(&v))
  42. return static_cast<T>(*ptr);
  43. throw std::bad_cast();
  44. }
  45. template <class T>
  46. T any_cast(Any&& v)
  47. {
  48. using U = std::remove_cv_t<std::remove_reference_t<T>>;
  49. static_assert(std::is_constructible_v<T, U>, "T must be a rvalue reference or a CopyConstructible type");
  50. if (auto ptr = std::any_cast<U>(&v))
  51. return static_cast<T>(std::move(*ptr));
  52. throw std::bad_cast();
  53. }
  54. } // namespace realm::util
  55. #endif // REALM_UTIL_ANY_HPP