Advertisement
luckytyphlosion

C++ templates

Aug 21st, 2021
1,817
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. #include <cstring>
  2. #include <type_traits>
  3.  
  4. // strcmp(handlers[i].inputFileExtension, inputFileExtension)
  5. // handlers[i].inputFileExtension.cmp(inputFileExtension)
  6.  
  7. enum Constness
  8. {
  9.     Nonconst,
  10.     NonConst = Nonconst,
  11.     Cnst,
  12.     Const = Cnst
  13. };
  14.  
  15. template<Constness flag, typename T, typename U>
  16. struct Select { typedef T Result; };
  17.  
  18. template<typename T, typename U>
  19. struct Select<Nonconst, T, U> { typedef U Result; };
  20.  
  21. template <Constness isConst = Nonconst>
  22. struct CString
  23. {
  24.     typedef typename Select<isConst, const char, char>::Result Char;
  25.     Char * data;
  26.  
  27.     CString(Char * data)
  28.     {
  29.         this->data = data;
  30.     }
  31.  
  32.     operator Char *()
  33.     {
  34.         return data;
  35.     }
  36.  
  37.  
  38.     Char& operator[](std::size_t idx)       { return this->data[idx]; }
  39.     Char& operator[](std::size_t idx) const { return this->data[idx]; }
  40.  
  41.     CString * operator=(CString * other)
  42.     {
  43.         this->data = other.data;
  44.         return *this;
  45.     }
  46.  
  47.     inline int cmp(const char * rhs) const {
  48.         return std::strcmp(this->data, rhs);
  49.     }
  50. };
  51.  
  52. struct CommandHandler
  53. {
  54.     CString<Const> inputFileExtension;
  55.     CString<> outputFileExtension;
  56. };
  57.  
  58. struct CommandHandler2
  59. {
  60.     const char * inputFileExtension;
  61.     char * outputFileExtension;
  62. };
  63.  
  64. char png_str1[] = "png";
  65. char png_str2[] = "png";
  66.  
  67. struct CommandHandler handlers[] =
  68. {
  69.     { "1bpp", png_str1},
  70.     { "4bpp", png_str2}
  71. };
  72.  
  73. struct CommandHandler2 handlers2[] =
  74. {
  75.     { "1bpp", png_str1},
  76.     { "4bpp", png_str2}
  77. };
  78.  
  79. int main2(const char * inputFileExtension)
  80. {
  81.     if (handlers[0].inputFileExtension.cmp(inputFileExtension) == 0) {
  82.         char t3bpp_str[] = "3bpp";
  83.         handlers[0].outputFileExtension = t3bpp_str;
  84.         handlers[0].inputFileExtension = "9bpp";
  85.         return 10;
  86.     } else {
  87.         return 17;
  88.     }
  89. }
  90.  
  91. int main3(const char * inputFileExtension)
  92. {
  93.     if (strcmp(handlers2[0].inputFileExtension, inputFileExtension) == 0) {
  94.         char t3bpp_str[] = "3bpp";
  95.         handlers2[0].outputFileExtension = t3bpp_str;
  96.         handlers2[0].inputFileExtension = "9bpp";
  97.         return 10;
  98.     } else {
  99.         return 17;
  100.     }
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement