Advertisement
Guest User

std::format automatically cast arbitrary pointers

a guest
Jul 27th, 2023
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.13 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <concepts>
  4. #include <type_traits>
  5. #include <format>
  6.  
  7. template <typename T>
  8. using base_type = std::remove_cvref_t<T>;
  9.  
  10. // clang-format off
  11. template <typename T>
  12. concept is_char_type = (
  13.   std::is_same_v<base_type<T>, const char *>    || std::is_same_v<base_type<T>, char *>    ||
  14.   std::is_same_v<base_type<T>, const char8_t*>  || std::is_same_v<base_type<T>, char8_t*>  ||
  15.   std::is_same_v<base_type<T>, const char16_t*> || std::is_same_v<base_type<T>, char16_t*> ||
  16.   std::is_same_v<base_type<T>, const char32_t*> || std::is_same_v<base_type<T>, char32_t*> ||
  17.   std::is_same_v<base_type<T>, const wchar_t*>  || std::is_same_v<base_type<T>, wchar_t*>
  18. );
  19.  
  20. // clang-format on
  21.  
  22. template <typename T>
  23. auto
  24. quit_helper (const T &_val)
  25. {
  26.   if constexpr (std::is_pointer_v<T> && !is_char_type<T>)
  27.     return static_cast<void *const> (_val);
  28.   else
  29.     return _val;
  30. }
  31.  
  32. template <typename T>
  33. auto
  34. quit_helper (T &_val)
  35. {
  36.   if constexpr (std::is_pointer_v<T> && !is_char_type<T>)
  37.     return static_cast<const void *> (_val);
  38.   else
  39.     return _val;
  40. }
  41.  
  42. /**
  43.  * @brief prints message according to provided arguments and calls
  44.  * std::exit(1), terminating the application
  45.  * @note Accepts stdlib string types
  46.  * @tparam Args Packed types
  47.  * @param fmt char type specifying how to format
  48.  * @param args packed parameters to format according @p fmt
  49.  */
  50. template <typename... Args>
  51. void
  52. quit (std::string &&fmt, Args &&...args)
  53. {
  54.   auto m = std::vformat (
  55.       std::string_view{ fmt },
  56.       std::make_format_args (quit_helper (std::forward<Args> (args))...));
  57.   std::cout << m << "\n";
  58.   std::exit (1);
  59. }
  60.  
  61. template <typename... Args>
  62. void
  63. quit (const char *fmt, Args &&...args)
  64. {
  65.   quit (std::string{ fmt }, std::forward<Args> (args)...);
  66. }
  67.  
  68. struct node {
  69.     int fake;
  70. };
  71.  
  72. struct game_object {
  73.     float x;
  74.     float y;
  75. };
  76.  
  77. int main() {
  78.     int a = 256;
  79.     bool b = false;
  80.     node* nptr = nullptr;
  81.     game_object* nptr2 = new game_object();
  82.     quit("Hello world, Int: {}, bool: {}, Arbritrary Ptr1: {} Abritrary Ptr2: {}", a, b, nptr, nptr2);
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement