Advertisement
Guest User

Trying to automatically cast T* to void* preserving constness for std::format() in c++

a guest
Jul 26th, 2023
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.17 KB | Source Code | 0 0
  1. template <typename T, typename Type = std::remove_reference<T>>
  2. concept is_non_pointer = (std::is_pointer_v<Type> == false);
  3.  
  4. template <typename T, typename Type = std::remove_reference<T>>
  5. concept is_const_pointer = (std::is_pointer_v<Type> && std::is_const_v<Type>);
  6.  
  7. template <typename T, typename Type = std::remove_reference<T>>
  8. concept is_non_const_pointer
  9.     = (std::is_pointer_v<Type> && (std::is_const_v<Type> == false));
  10.  
  11. /**
  12.  * @brief General helper, just takes non pointers and forwards them
  13.  */
  14. template <typename _T>
  15. requires is_non_pointer<_T>
  16. auto &&
  17. quit_helper (_T &&val)
  18. {
  19.   return std::forward<_T> (val);
  20. }
  21.  
  22. /**
  23.  * @brief Takes a const T* and reinterpret_cast<> to const void*
  24.  * @note This method is for const pointers
  25.  * @returns const T* => const void*
  26.  */
  27. template <typename _T>
  28. requires is_const_pointer<_T>
  29. auto
  30. quit_helper (_T val)
  31. {
  32.   static_assert (sizeof (_T) == sizeof (const void *));
  33.   return static_cast<const void *> (std::remove_reference<_T> (val));
  34. }
  35.  
  36. /**
  37.  * @brief Takes a T* and reinterpret_cast<> to void*
  38.  * @note This method is for non-const pointers only.
  39.  * @returns T* => void*
  40.  */
  41. template <typename _T>
  42. requires is_non_const_pointer<_T>
  43. auto
  44. quit_helper (_T val)
  45. {
  46.   static_assert (sizeof (_T) == sizeof (void *));
  47.   return static_cast<void *> (val);
  48. }
  49.  
  50. /**
  51.  * @brief prints message according to provided arguments and calls
  52.  * std::exit(1), terminating the application
  53.  * @tparam Args Packed types
  54.  * @param fmt char type specifying how to format
  55.  * @param args packed parameters to format according @p fmt
  56.  */
  57. template <typename... Args>
  58. void
  59. quit (std::string_view fmt, Args &&...args)
  60. {
  61.   auto m = std::vformat (
  62.       std::string_view{ fmt },
  63.       std::make_format_args (quit_helper (std::forward<Args> (args))...));
  64.   std::cout << m << "\n";
  65.   std::exit (1);
  66. }
  67.  
  68. template <typename... Args>
  69. void
  70. quit (std::string &fmt, Args &&...args)
  71. {
  72.   auto sfmt = std::string_view{ fmt };
  73.   quit (sfmt, std::forward<Args> (args)...);
  74. }
  75.  
  76. template <typename... Args>
  77. void
  78. quit (const char *fmt, Args &&...args)
  79. {
  80.   auto sfmt = std::string_view{ fmt };
  81.   quit (sfmt, std::forward<Args> (args)...);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement