Cast.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Cast.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include <typeinfo>
  12. #include <string>
  13. #include "CTypeList.h"
  14. template<class T, class F>
  15. inline const T * dynamic_ptr_cast(const F * ptr)
  16. {
  17. #ifndef VCMI_APPLE
  18. return dynamic_cast<const T *>(ptr);
  19. #else
  20. if(!strcmp(typeid(*ptr).name(), typeid(T).name()))
  21. {
  22. return static_cast<const T *>(ptr);
  23. }
  24. try
  25. {
  26. auto * sourceTypeInfo = typeList.getTypeInfo(ptr);
  27. auto * targetTypeInfo = &typeid(typename std::remove_const<typename std::remove_pointer<T>::type>::type);
  28. typeList.castRaw((void *)ptr, sourceTypeInfo, targetTypeInfo);
  29. }
  30. catch(...)
  31. {
  32. return nullptr;
  33. }
  34. return static_cast<const T *>(ptr);
  35. #endif
  36. }
  37. template<class T, class F>
  38. inline T * dynamic_ptr_cast(F * ptr)
  39. {
  40. #ifndef VCMI_APPLE
  41. return dynamic_cast<T *>(ptr);
  42. #else
  43. if(!strcmp(typeid(*ptr).name(), typeid(T).name()))
  44. {
  45. return static_cast<T *>(ptr);
  46. }
  47. try
  48. {
  49. auto * sourceTypeInfo = typeList.getTypeInfo(ptr);
  50. auto * targetTypeInfo = &typeid(typename std::remove_const<typename std::remove_pointer<T>::type>::type);
  51. typeList.castRaw((void *)ptr, sourceTypeInfo, targetTypeInfo);
  52. }
  53. catch(...)
  54. {
  55. return nullptr;
  56. }
  57. return static_cast<T *>(ptr);
  58. #endif
  59. }