以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 8k79&|
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 31)&vf[[
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 P2Y^d#jO
象当作char数组来处理。 d5d@k
template<class Container> `h;[TtIX4
class bit_iterator : public std::iterator<bidirectional_iterator_tag, >sbu<|]a
7
void, void> S>{~nOYt-`
{ =c7;r]Ol
public: n !(F, b
explicit bit_iterator(Container& c) : m_container(&c) /RF7j;
{ kVL.PY\K
m_size = 8*sizeof(Container); 7z-[f'EIUI
m_index = 0; pk~WrqK}
} M=Wz
explicit bit_iterator() : m_container(0) )e{}V\;q
{ QW"! (`K
m_size = 8*sizeof(Container); MQ4KdqgP
m_index = m_size; $!DpjN
} %)wjR/o
bool operator* () \v/[6&|X0s
{ 45oR=Atn
char mask = 1; 0IpmRH/
char* pc = (char*)m_container; /tLVX} &
int i = (m_size-m_index-1)/8; ;rS{:
int off = (m_size-m_index-1)%8; @|r{;'
mask <<=off; F}zDfY\-
return pc & mask; I_BJH'!t
} ~s{$WL&
bit_iterator<Container>& operator++() svSVG:48
{ f 1d?.)
m_index++; /O9EQ Pm(
return *this; KmF]\:sMD
} > P)w?:k
bit_iterator<Container>& operator++(int) Wjc'*QCPl
{ e# bn#
m_index++; 54/=G(F
return *this; y)*RV;^
} H>C=zo,oiC
bool operator==(bit_iterator<Container>& bitIt) Cyp'?N
{ olcDt&xv]
return m_index == bitIt.m_index; Y$zSQ_k;U
} Q.[0ct
bool operator!=(bit_iterator<Container>& bitIt) O@P"MXEG
{ 9B4&m|g
return !(*this == bitIt); K%d&EYoW]
} 0aAoV0fMDz
protected: 2?x4vI
np;
Container* m_container; H#&00 Q[
private: h$*!8=M
int m_size; Ls%MGs9PI
int m_index; `2snz1>!j
}; _Y!IEAU/#
8-i#8'/x
用该迭代器可以将任意类型对象以二进制格式输出: n| ;Im&,
double a = 10; 6wxs1G
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));