memory 867 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // -*-c++-*-
  2. // vim: set ft=cpp:
  3. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  4. file Copyright.txt or https://cmake.org/licensing for details. */
  5. #ifndef cmext_memory
  6. #define cmext_memory
  7. #include <typeinfo>
  8. #include <cm/type_traits>
  9. namespace cm {
  10. template <typename T, typename O,
  11. cm::enable_if_t<
  12. std::is_pointer<cm::invoke_result_t<decltype(&O::get), O>>::value,
  13. int> = 0>
  14. T& static_reference_cast(O& item)
  15. {
  16. return *(static_cast<T*>(item.get()));
  17. }
  18. template <typename T, typename O,
  19. cm::enable_if_t<
  20. std::is_pointer<cm::invoke_result_t<decltype(&O::get), O>>::value,
  21. int> = 0>
  22. T& dynamic_reference_cast(O& item)
  23. {
  24. auto p = dynamic_cast<T*>(item.get());
  25. if (p == nullptr) {
  26. throw std::bad_cast();
  27. }
  28. return *p;
  29. }
  30. } // namespace cm
  31. #endif