以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 )'%L#
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 _a*Wk
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 21 cB_"
象当作char数组来处理。 z!Jce}mx
template<class Container> 3SQ
5C'E
class bit_iterator : public std::iterator<bidirectional_iterator_tag, )X\3bPDJR
void, void>
wSV[nK
{ _* 4
<
public: )#3,y6
explicit bit_iterator(Container& c) : m_container(&c) TdD-#|5
{ !0Xes0gK0
m_size = 8*sizeof(Container); 8qBRO[
m_index = 0; RW>Z~Nj
} ? dSrY
explicit bit_iterator() : m_container(0) 2%vwC]A
{ @u6#Tvxy[
m_size = 8*sizeof(Container); f$V']dOj1q
m_index = m_size; {br4B7b
} =]W{u`
bool operator* () 5bmtUIj
{ )IZ$R*Y{
char mask = 1; #FaR?L![Y
char* pc = (char*)m_container; !;CY
@=
int i = (m_size-m_index-1)/8; 0]>p|m9K^<
int off = (m_size-m_index-1)%8; mq'q@@:c
mask <<=off; 6t]oSxN
return pc & mask; #3u8BLy$Q
} =K8`[iH
bit_iterator<Container>& operator++() Q1eiU Y6
{ |7%$+g
m_index++; Y!&dj95y
return *this; >47,Hq:2
} uX}M0W
bit_iterator<Container>& operator++(int) by6E
"7%
{ `5 e#9@/e
m_index++; NqqLRgMOR'
return *this; t4s}w$4
} C?x
bool operator==(bit_iterator<Container>& bitIt) _IpW&
{ (2qo9j"j/Y
return m_index == bitIt.m_index; B0Z*YsbXL
} L4kYF~G:4
bool operator!=(bit_iterator<Container>& bitIt) r="X\ [on
{ 5+3Z?|b
return !(*this == bitIt); ,st4K;-
} $#Ji=JX
protected: u> >t"w
Container* m_container; 0HxF#SlKM
private: -JwH^*Ad
int m_size; fngZ0k!
int m_index; |Ca$>]?
}; )sNtwSl^
3wR5:O$H
用该迭代器可以将任意类型对象以二进制格式输出: N;[w`d'#
double a = 10; +}9%Duim
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));