Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. // ******************* Вариант 1 ********************
  2. // Не удалось загрузить текстуру - да и хрен с ним. Не мои проблемы. Я устал, я ухожу.
  3.  
  4. #define LOG_ERROR(msg) do { fprintf(stderr, msg); std::terminate(); } while (false)
  5.  
  6. class Texture {
  7. public:
  8.     Texture(const std::string_view path) {
  9.         uint8_t *pixels = somelib_load_image(path);
  10.         if (!pixels) {
  11.             LOG_ERROR("failed to load image " + path);
  12.         }
  13.     }
  14. };
  15.  
  16. // ******************* Вариант 2 ********************
  17. // Не удалось загрузить текстуру - кину исключение, которое можно обработать
  18.  
  19. class FileNotFound : std::exception {
  20. public:
  21.     FileNotFound(const std::string_view msg) {
  22.         fprintf(stderr, msg);
  23.     }
  24. };
  25.  
  26. class Texture {
  27. public:
  28.     Texture(const std::string_view path) {
  29.         uint8_t *pixels = somelib_load_image(path);
  30.         if (!pixels) {
  31.             throw FileNotFound("failed to load image " + path);
  32.         }
  33.     }
  34. };
  35.  
  36. try {
  37.     auto texture = Texture("nonexistent.png");
  38. }
  39. catch (const FileNotFound &e) {
  40.     ...
  41. }
  42.  
  43. // ******************* Вариант 3 ********************
  44. // Не удалось загрузить текстуру - верну ошибку, с которой можно что-то сделать уровнем выше
  45.  
  46. class Texture {
  47. public:
  48.     static std::expected<Texture, std::string> createFromFile(const std::string_view path) {
  49.         uint8_t *pixels = somelib_load_image(path);
  50.         if (!pixels) {
  51.             return std::make_unexpected("failed to load image " + path);
  52.         }
  53.         return Texture(pixels);
  54.     }
  55.    
  56. private:
  57.     Texture(uint8_t *pixels);
  58. };
  59.  
  60. auto texture = Texture::createFromFile("nonexistent.png");
  61. if (texture) {
  62.     ...
  63. }
  64. else {
  65.     ...
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement