以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 q h/F
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 {-3L IO
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 VhL{'w7f
象当作char数组来处理。 A4C+5R
template<class Container> ({r*=wAP
class bit_iterator : public std::iterator<bidirectional_iterator_tag, #LlUxHv #
void, void> 3_Cp%~Gi-_
{ VKp*9%9
public: fhPkEvJ
explicit bit_iterator(Container& c) : m_container(&c) Sr?#wev]rn
{ O.aG[wm8
m_size = 8*sizeof(Container); cH'
iA.
m_index = 0; -l~Z0U>^
} W%<LTWOc
explicit bit_iterator() : m_container(0) 2. G=8:l
{ b-ll
m_size = 8*sizeof(Container); fmqb`%
m_index = m_size; v
^[39*8
} F{06 _T
bool operator* () {]_uMg#!
{ [^CV>RuO
char mask = 1; [.se|]t7X
char* pc = (char*)m_container; N`iwC!
int i = (m_size-m_index-1)/8; PZxAH9 S?
int off = (m_size-m_index-1)%8; <+MyZM(z>
mask <<=off; -fhN"B)
return pc & mask; L`f^y;Y.
} U,#yqER'r
bit_iterator<Container>& operator++() o#) {1<0vg
{ x:-.+C%
m_index++; Z4<L$i;/jN
return *this; T|J9cgtS
} L86n}+
P\
bit_iterator<Container>& operator++(int) E )Gw0]G
{ 2M#M"LHo
m_index++; Q!-
0xlx
return *this; <,o>Wx*1C
} W} WI; cI
bool operator==(bit_iterator<Container>& bitIt) ^b: (jI*l
{ .2d9?p3Y
return m_index == bitIt.m_index; :w}{$v}#D;
} T134ZXqqz
bool operator!=(bit_iterator<Container>& bitIt) !cKz7?w
{ =qN2Xg/
return !(*this == bitIt); rpeJkG@+
} SJD@&m%?[
protected: u\&b4=nL
Container* m_container; 5T sU Qc
private: 8.F~k~srA
int m_size; F,
U*yj
int m_index; @SCI"H%[
}; mF` B#
UOQEk22
用该迭代器可以将任意类型对象以二进制格式输出: c/c$D;T
double a = 10; }Zl&]e
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));