以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 \1 ^qfw
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 ,[ogh
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 Y(:.f-Du
象当作char数组来处理。 O(P
,!
template<class Container> 47(/K2
class bit_iterator : public std::iterator<bidirectional_iterator_tag, hvc%6A\nm
void, void> \I3={ii0
{ ]7#@lL;'0
public: wF@mHv
explicit bit_iterator(Container& c) : m_container(&c) .bwKG`F
{ Hh|a(Zq,
m_size = 8*sizeof(Container); |G!P G6%1
m_index = 0; ^+v6?%m
} p-KMELB
explicit bit_iterator() : m_container(0) AdCi*="m
{ t&GjW6]W
m_size = 8*sizeof(Container); ch^tq",1>
m_index = m_size; )_7OHV *3
} Jl,mYFEZ
bool operator* () YLEk
M
{ #7wOr78
char mask = 1; #fF~6wopV
char* pc = (char*)m_container; 6f$h1$$)^
int i = (m_size-m_index-1)/8; jjs1Vj1@<
int off = (m_size-m_index-1)%8; uude<d"U
mask <<=off; <%@S-+D`]
return pc & mask; ~-1!?t/%
} q;XO1Se
bit_iterator<Container>& operator++() z j[/~I
{ !A5UT-
m_index++; $U{\T4
return *this; O{B[iy(C
} 5>o<!0g
bit_iterator<Container>& operator++(int) 2E@ !
{ ]w)*8
w.)
m_index++; @R!f(\
return *this; EPY64{
} dWg09 sx
bool operator==(bit_iterator<Container>& bitIt) t1y
hU"(J
{ [CCj5N1/
return m_index == bitIt.m_index; 3I rmDT
} ^t|CD|,K_O
bool operator!=(bit_iterator<Container>& bitIt) *2$I,
~(P
{ <