Advertisement
homer512

C++11 enum attribute set template

Jul 21st, 2013
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. /*
  2.  * Copyright 2013 Florian Philipp
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  * http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16. #include <bitset>
  17. #include <cassert>
  18.  
  19. namespace {
  20.  
  21.   template<class EnumClass, EnumClass min, EnumClass max>
  22.   class EnumSet
  23.   {
  24.     /* static_cast to size_t works in all cases, even when underlying enum
  25.      * values are negative
  26.      */
  27.     typedef std::bitset<
  28.       static_cast<std::size_t>(max) - static_cast<std::size_t>(min) + 1> set_t;
  29.     set_t set;
  30.   public:
  31.     typedef typename set_t::reference reference;
  32.     reference operator[](EnumClass e)
  33.     {
  34.       return set[static_cast<std::size_t>(e) - static_cast<std::size_t>(min)];
  35.     }
  36.     bool operator[](EnumClass e) const
  37.     {
  38.       return set[static_cast<std::size_t>(e) - static_cast<std::size_t>(min)];
  39.     }
  40.   };
  41.   enum class Source {
  42.     analog_radio, internet_radio, bluetooth
  43.   };
  44.   typedef EnumSet<Source, Source::analog_radio, Source::bluetooth> SourceSet;
  45. }
  46.  
  47. int main()
  48. {
  49.   SourceSet attributes;
  50.   attributes[Source::analog_radio] = true;
  51.   attributes[Source::bluetooth] = true;
  52.   assert(attributes[Source::analog_radio] == true);
  53.   assert(attributes[Source::internet_radio] == false);
  54.   assert(attributes[Source::bluetooth] == true);
  55.   return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement