bits.hpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*-----------------------------------------------------------------------------+
  2. Author: Joachim Faulhaber
  3. Copyright (c) 2009-2009: Joachim Faulhaber
  4. +------------------------------------------------------------------------------+
  5. Distributed under the Boost Software License, Version 1.0.
  6. (See accompanying file LICENCE.txt or copy at
  7. http://www.boost.org/LICENSE_1_0.txt)
  8. +-----------------------------------------------------------------------------*/
  9. #ifndef BOOST_LIBS_ICL_EXAMPLE_LARGE_BITSET_BITS_HPP_JOFA_091019
  10. #define BOOST_LIBS_ICL_EXAMPLE_LARGE_BITSET_BITS_HPP_JOFA_091019
  11. //[mini_bits_includes
  12. // These includes are needed ...
  13. #include <string> // for conversion to output and to
  14. #include <boost/icl/type_traits/has_set_semantics.hpp>//declare that bits has the
  15. // behavior of a set.
  16. //]
  17. namespace mini
  18. {
  19. //[mini_bits_class_bits
  20. template<class NaturalT> class bits
  21. {
  22. public:
  23. typedef NaturalT word_type;
  24. static const int digits = std::numeric_limits<NaturalT>::digits;
  25. static const word_type w1 = static_cast<NaturalT>(1) ;
  26. bits():_bits(){}
  27. explicit bits(word_type value):_bits(value){}
  28. word_type word()const{ return _bits; }
  29. bits& operator |= (const bits& value){_bits |= value._bits; return *this;}
  30. bits& operator &= (const bits& value){_bits &= value._bits; return *this;}
  31. bits& operator ^= (const bits& value){_bits ^= value._bits; return *this;}
  32. bits operator ~ ()const { return bits(~_bits); }
  33. bool operator < (const bits& value)const{return _bits < value._bits;}
  34. bool operator == (const bits& value)const{return _bits == value._bits;}
  35. bool contains(word_type element)const{ return ((w1 << element) & _bits) != 0; }
  36. std::string as_string(const char off_on[2] = " 1")const;
  37. private:
  38. word_type _bits;
  39. };
  40. //]
  41. template<class NaturalT>
  42. std::string bits<NaturalT>::as_string(const char off_on[2])const
  43. {
  44. std::string sequence;
  45. for(int bit=0; bit < digits; bit++)
  46. sequence += contains(bit) ? off_on[1] : off_on[0];
  47. return sequence;
  48. }
  49. } // mini
  50. //[mini_bits_is_set
  51. namespace boost { namespace icl
  52. {
  53. template<class NaturalT>
  54. struct is_set<mini::bits<NaturalT> >
  55. {
  56. typedef is_set<mini::bits<NaturalT> > type;
  57. BOOST_STATIC_CONSTANT(bool, value = true);
  58. };
  59. template<class NaturalT>
  60. struct has_set_semantics<mini::bits<NaturalT> >
  61. {
  62. typedef has_set_semantics<mini::bits<NaturalT> > type;
  63. BOOST_STATIC_CONSTANT(bool, value = true);
  64. };
  65. }}
  66. //]
  67. #endif