以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 cd;~60@K
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 NdB:2P
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 ,S?M;n?z_
象当作char数组来处理。 Ee^>Q*wahw
template<class Container> zYEb#*Kar
class bit_iterator : public std::iterator<bidirectional_iterator_tag, <f;Xs(
void, void> |N0RBa4%
{ {2LG$x-N%
public: w|:ev_c|
explicit bit_iterator(Container& c) : m_container(&c) {j%7/T{
{ /\U:F
m_size = 8*sizeof(Container); Go
!{T
m_index = 0; `!C5"i8+i2
} PoZxT-U
explicit bit_iterator() : m_container(0) FSb4RuD9
{ 6SEq 2
m_size = 8*sizeof(Container); !H(V%B%
m_index = m_size; F6Qnz8|
} :Fi$-g
bool operator* () %t%D|cf
{ `.F3&pA
char mask = 1; #@<L$"L
char* pc = (char*)m_container; pDt45
int i = (m_size-m_index-1)/8; g:?p/L
int off = (m_size-m_index-1)%8; _+d*ljP)l3
mask <<=off; xzBUm
return pc & mask; :z2G
a
} +THK
Jn!>
bit_iterator<Container>& operator++() aK--D2@}i
{ 9:7&`JlC#
m_index++;
d_ji
..T
return *this; oG=4&SQ
} T&->xef=
bit_iterator<Container>& operator++(int) yK0iW
{ i'z(`"
m_index++; uHPd!#]
return *this; u2cDSRrqT
} Ub`vf4EB
bool operator==(bit_iterator<Container>& bitIt) w~>tpkUB
{ c"pu"t@/Z
return m_index == bitIt.m_index; gb/<(I )
} :_kZkWD5
bool operator!=(bit_iterator<Container>& bitIt) bdHHOpXM
{ Q@/Z~xw"'I
return !(*this == bitIt); 8>[o.xV
} >n jX=r.
protected: y>] Yq-
Container* m_container;
BO'7c1FU
private: < mp_[-c
int m_size; v8>bR|n5
int m_index; AL*M`m_
}; u_6x{",5I
Jm,tN/o*
用该迭代器可以将任意类型对象以二进制格式输出: &e99P{\D
double a = 10; !rff/0/x"
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));