Advertisement
Guest User

Untitled

a guest
Nov 26th, 2024
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 KB | Source Code | 0 0
  1. #include <string>
  2.  
  3. class Enum1
  4. {
  5. public:
  6.     enum EnumerationItem
  7.     {
  8.         BEARS1,
  9.         BEARS2,
  10.         BEARS3
  11.     };
  12.  
  13.     static std::string toString(EnumerationItem e)
  14.     {
  15.         switch(e)
  16.         {
  17.             case BEARS1: return "BEARS1";
  18.             case BEARS2: return "BEARS2";
  19.             case BEARS3: return "BEARS3";
  20.                 // Should ideally throw an exception
  21.             default: return "";
  22.         }
  23.     }
  24. };
  25.  
  26. class Enum2
  27. {
  28. public:
  29.     enum EnumerationItem
  30.     {
  31.         TIGERS1,
  32.         TIGERS2,
  33.         TIGERS3
  34.     };
  35.  
  36.     static std::string toString(EnumerationItem e)
  37.     {
  38.         switch(e)
  39.         {
  40.             case TIGERS1: return "TIGERS1";
  41.             case TIGERS2: return "TIGERS2";
  42.             case TIGERS3: return "TIGERS3";
  43.                 // Should ideally throw an exception
  44.             default: return "";
  45.         }
  46.     }
  47. };
  48.  
  49. template <typename T>
  50. class TemplateExample
  51. {
  52. public:
  53.     using Enumeration = typename T::EnumerationItem;
  54.  
  55. public:
  56.     TemplateExample(Enumeration e)
  57.         : e { e } {}
  58.  
  59.     virtual ~TemplateExample() {}
  60.  
  61.     std::string toString()
  62.     {
  63.         return T::toString(this->e);
  64.     }
  65.  
  66. private:
  67.     Enumeration e;
  68. };
  69.  
  70. int main()
  71. {
  72.     TemplateExample<Enum1> t1(Enum1::EnumerationItem::BEARS1);
  73.     TemplateExample<Enum2> t2(Enum2::EnumerationItem::TIGERS3);
  74.  
  75.     std::cout << t1.toString() << std::endl;
  76.     std::cout << t2.toString() << std::endl;
  77.  
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement