以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 t=K;/1
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 )}G?^rDH(
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 O]XdPH20
象当作char数组来处理。 y,i ~w |4
template<class Container> C0eqCu)Q
class bit_iterator : public std::iterator<bidirectional_iterator_tag, 5)T=^"IHXi
void, void> 8@}R_GZc
{ iPD5
KsAOA
public: Qh0tU<jG
explicit bit_iterator(Container& c) : m_container(&c) cIm_~HH
{ [\Ks+S
m_size = 8*sizeof(Container); /YyimG7
m_index = 0; d-W@/J
} M<A jtDF%
explicit bit_iterator() : m_container(0) wfecM(
{ THQd`Lj
m_size = 8*sizeof(Container); &pL.hM^
m_index = m_size; ^tw\F7
} o!\Q,
bool operator* () ']bpsn
{ xD:t$~
char mask = 1; dTE(+M-
Gr
char* pc = (char*)m_container; {pV\]E\]
int i = (m_size-m_index-1)/8; efc<lSUR
int off = (m_size-m_index-1)%8; 2/T4.[`t
mask <<=off; vM.Y/,7S
return pc & mask; jo7`DDb
} q{fgsc8v\
bit_iterator<Container>& operator++() _RT JEG
{ WDM^rjA|j
m_index++; x)wlp{rLf
return *this; k3pY3TA@w+
} 1\[En/6
bit_iterator<Container>& operator++(int) }!&Vc f
{ ?4[IIX-
m_index++; ![>j`i
return *this; _SW_I{fjr
} K;,_P5J%
bool operator==(bit_iterator<Container>& bitIt) \V1geSoE
{ EAdr}io
return m_index == bitIt.m_index; 8zOoVO
} oy;g;dtq
bool operator!=(bit_iterator<Container>& bitIt) DCv=*=6w
{ 75^U<Hz-3{
return !(*this == bitIt); D~(f7~c%
} -$x5[6bN
protected: + YjK#
Container* m_container; +K@wh
private: z;VAi=m
q
int m_size; S4salpz
int m_index; w;p:4`
}; #Yqj27&
y{?wxg9
用该迭代器可以将任意类型对象以二进制格式输出: Fm| h3.`V
double a = 10; Y`U[Y Hx
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));