以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 ,zY$8y]
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 Pgea NK5Y
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 Q]>.b%s[
象当作char数组来处理。 N] sAji*
template<class Container> I~XSn>-H
class bit_iterator : public std::iterator<bidirectional_iterator_tag, Z#\P&\`1z
void, void> q'82qY
{ J-hbh
public: 4{`{WI{
explicit bit_iterator(Container& c) : m_container(&c) 5XBH$&Td
{ MFk5K
m_size = 8*sizeof(Container); R~$qo)v
m_index = 0; gB'6`'
} G'A R`"F
explicit bit_iterator() : m_container(0) wAW5
Z0D
{ LFtt gY
m_size = 8*sizeof(Container); g}',(tPMZ
m_index = m_size; _5N]B|cO
} uW36;3[f#1
bool operator* () n6a`;0f[R
{ oILZgNe'
char mask = 1; y
h9*z3
char* pc = (char*)m_container; @I!0-OjL
int i = (m_size-m_index-1)/8; 3/n5#&c\4
int off = (m_size-m_index-1)%8; }9fTF:P
mask <<=off; e**qF=HCw
return pc & mask; "LTad`]<Ro
} <W $mj04@
bit_iterator<Container>& operator++() ,DkNLE
{ W:L
AP
R
m_index++; 9;-p'C
return *this; *bA.zmzM
} O@C@eW#
bit_iterator<Container>& operator++(int) r\V
={p
{ NHZz _a=
m_index++; ^$hH1H+V
return *this; |8tilOqI
} H~1jY4E
bool operator==(bit_iterator<Container>& bitIt) QB'aON\S
{ A2jUmK.&
return m_index == bitIt.m_index; *CI#+P
} G*P#]eO
bool operator!=(bit_iterator<Container>& bitIt) 81
sG
{ [E juUElr
return !(*this == bitIt); ,1o FPa{?
} 5C5sgR C
protected:
]-/VHh
Container* m_container; ckE-",G
private: Dwfu.ZJa
int m_size; 'AS|ZRr/
int m_index; y/ef>ZZ
};
Qjv}$`M
ZX./P0
用该迭代器可以将任意类型对象以二进制格式输出: 338k?nHxv
double a = 10; e h?zNu2=
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));