Miguel Tadeu
Posts: 1
Nickname: mtadeunet
Registered: Nov, 2007
|
|
Re: Why not C bitfields?
|
Posted: Nov 12, 2007 10:36 AM
|
|
I read a book that noted just that(can remember which), but I picked the example described there and added a few features: // from the book template<unsigned long N> struct binary { static const unsigned int digit = N % 10; BOOST_STATIC_ASSERT(digit == 0 || digit == 1); static unsigned long const value = binary<N/10>::value * 2 + digit; };
template<> struct binary<0> { static unsigned int const value = 0; };
// from me... template<unsigned long N, unsigned long S> struct binary_shift_left : binary<N> { static unsigned long const value = (binary<N>::value << S); };
template<unsigned long N, unsigned long S> struct binary_shift_right : binary<N> { static unsigned long const value = (binary<N>::value >> S); };
template<unsigned long N, unsigned long P = 0> struct flag : binary_shift_left<N, P> { };
template<unsigned long P> struct bit_flag : flag<1, P>{ };
// usage int main(int argc, char *argv[]) { unsigned long flags = 0x00;
flags = binary<1010101010>::value; flags |= bit_flag< 1 >::value; flags |= bit_flag< 2 >::value; flags |= bit_flag< 3 >::value; flags |= bit_flag< 4 >::value; flags |= bit_flag< 5 >::value; flags |= bit_flag< 6 >::value; flags |= bit_flag< 7 >::value; flags |= bit_flag< 8 >::value; flags |= flag<11, 9>::value | flag<101, 5>::value;
cout << binary<1111>::value << endl;
return EXIT_SUCCESS; }
It's to be noticed that recent compilers will resolve the templates and the code remains as optimized as in C.
|
|