以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 lplEQ]J|
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 ` =RJ8u
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 #Sr_PEo
_
象当作char数组来处理。 57Q^"sl
template<class Container> h!?7I=p~#
class bit_iterator : public std::iterator<bidirectional_iterator_tag, y~w2^VN=
void, void> w7$*J:{
{ Q9H~B`\nQ
public: D'F=v\P
explicit bit_iterator(Container& c) : m_container(&c) f ."bq43(
{ ~C6d5\
m_size = 8*sizeof(Container); ?1K|.lr
m_index = 0; 3xWeN#T0
} v}!eJzeH
explicit bit_iterator() : m_container(0) >t&Frw/Bl
{ `$\g8Mo
m_size = 8*sizeof(Container); 4pq@o
m_index = m_size; X(U
CN0#
} 1@6dHFA`o
bool operator* ()
/L'r
L
{ TYGUB%A
char mask = 1; V.vA~a
char* pc = (char*)m_container; t&T0E.kh*X
int i = (m_size-m_index-1)/8; &[f.;1+C
int off = (m_size-m_index-1)%8; ~0,Utqy
mask <<=off; s9>f5u?dK
return pc & mask; Q0i.gEwe
} iY1%"x
bit_iterator<Container>& operator++() @cA`del
{ d!5C$C/x
m_index++; x+x6F
return *this; +!6aB|-
} "rOe J~4 X
bit_iterator<Container>& operator++(int) $@"o BCc
{ yT%"<m6Y*\
m_index++; >!MOgLO3
return *this; ^E*W
B~
} sy=M#WGS
bool operator==(bit_iterator<Container>& bitIt) %Sr/'7 K
{ ZdJwy%
return m_index == bitIt.m_index;
I&?(=i)N
} q{5wx8_U
bool operator!=(bit_iterator<Container>& bitIt) /L\]t
{ #;sUAR?]
return !(*this == bitIt); 5@ecZ2`)+h
} mD{<Lp=
protected:
DvCs 5
Container* m_container; u[q1]]
private: -B-?z?+(O
int m_size; l2QO\O
I9m
int m_index;
]fvU}4!
}; 4nQk*:p(X
=p,+a/*
用该迭代器可以将任意类型对象以二进制格式输出: WL$nchS9
double a = 10; aT1T.3 a
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));