以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 =E!Y f#p+q
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 (`#z@,1
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 3'i(wI~<[
象当作char数组来处理。 aqK+ u.H
template<class Container> \JR^uJ{Y
class bit_iterator : public std::iterator<bidirectional_iterator_tag, -(lP8Y~gFY
void, void> b+arnKo1fk
{ O
x`K7$)
public: 6;s[dw5T
explicit bit_iterator(Container& c) : m_container(&c) W?kJ+1"(
{ CSW+UaE
m_size = 8*sizeof(Container); NMhpKno
m_index = 0; n q>F_h
} u&TXN;I,p
explicit bit_iterator() : m_container(0) nnT#S
{ XHJ`C\xR
m_size = 8*sizeof(Container); a-FI`Dv
m_index = m_size; 5#X R1#`
} /uR/,R++
bool operator* () biw .
~
{ ,=G]tnsv^
char mask = 1; [\h?mlG?
char* pc = (char*)m_container; 0&CXR=U5
int i = (m_size-m_index-1)/8; HIE8@Rv/3
int off = (m_size-m_index-1)%8; Z1($9hE>
mask <<=off; z'1%%.r;FM
return pc & mask; CDuA2e
} ]i0=3H2
bit_iterator<Container>& operator++() W4k$m2
{ +zLw%WD[l
m_index++; -z-yk~F
return *this; /|}yf/^9X
} ),Yk53G6c
bit_iterator<Container>& operator++(int) kkb+qo
{ @Y.r ,q
m_index++; -K8F$\W
return *this; E 11C@%
} GRofOJ
bool operator==(bit_iterator<Container>& bitIt) Rmn{Vui9\
{ i_r708ep6
return m_index == bitIt.m_index; {29aNm
} IDos4nM27]
bool operator!=(bit_iterator<Container>& bitIt) =v<A&4
{ Ck%if
return !(*this == bitIt); ;Sg.E8
} .b<W*4{j0H
protected: A:Gd F-;[
Container* m_container; 8qw{e`c
private: c[ 0`8s!
int m_size; 4J(-~
int m_index; y`7<c5zD
}; M&faa7
srO>l ;Vf/
用该迭代器可以将任意类型对象以二进制格式输出: 6H U*,
double a = 10; 6~W@$SP,F
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));