Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. namespace col_enum {
  2.  
  3.    template<class enum_t>
  4.    inline auto operator+(enum_t e) noexcept
  5.    {
  6.        static_assert(std::is_enum_v<enum_t>, "Only for enums!!");
  7.        return std::underlying_type<enum_t>(e);
  8.    }
  9.  
  10.    template<class enum_t>
  11.    inline std::string title(enum_t e); // Header title / string version of the enum
  12.  
  13.    template<class enum_t>
  14.    inline std::enable_if_t<std::is_enum_v<enum_t>::value, std::ostream&>
  15.    operator<<(std::ostream& os, enum_t e)
  16.    { return os << title(e); }
  17.  
  18.    template<class enum_t>
  19.    inline auto& operator++(enum_t& e) noexcept
  20.    { return e = enum_t(+e + 1); }
  21.  
  22.    // "Table size"
  23.    template<class enum_t>
  24.    constexpr std::size_t size() noexcept;
  25.  
  26.    // We assume one is an enumerator and the other
  27.    // is an integral type, or two enumerators of same type.
  28.    // For simplicity, no further check is done (it should though).
  29.    template<class a_t, class b_t>
  30.    inline bool operator==(a_t const& a, b_t const& b)
  31.    {
  32.       using cmp_t = std::common_type_t<decltype(+a), decltype(+b)>;
  33.       return static_cast<cmp_t>(a) == static_cast<cmp_t>(b);
  34.    }
  35.  
  36.    template<class a_t, class b_t>
  37.    inline bool operator!=(a_t a, b_t b) { return !(a == b); }
  38.  
  39.    // Any other "enumerator-member" or operator, if needed.
  40. }
  41.  
  42. // User-code
  43. namespace col_enum {
  44.    enum class table1_col { id, name };
  45.  
  46.    template<>
  47.    constexpr std::size_t size<table1_col>() noexcept { return 2; }
  48.  
  49.    template<>
  50.    inline std::string title<table1_col>(table1_col c)
  51.    {
  52.       switch(c) {
  53.       case table1_col::id:
  54.          return "ID";
  55.       case table1_col::name:
  56.          return "name";
  57.       default:
  58.          throw std::logic_error("invalid col");
  59.       }
  60.    }
  61. }
  62.  
  63. namespace col_enum {
  64.     // Other enumerator for other table,
  65.     // with their corresponding methods.
  66. }
  67.  
  68. class my_table1_model
  69. {
  70. public:
  71.   using col_t = col_enum::table1_col;
  72.   // ...
  73.  
  74.   void fun(int c)
  75.   {
  76.      if (c >= col_enum::size<col_t>())
  77.         throw std::logic_error("Whaaat?");
  78.  
  79.      if (c == col_t::id)
  80.         third_party_fun(this, +col_t::name,
  81.                         boost::lexical_cast<std::string>(col_t::name));
  82.   }
  83. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement