基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对
象当作char数组来处理。
template<class Container>
class bit_iterator : public std::iterator<bidirectional_iterator_tag,
void, void>
{
public:
explicit bit_iterator(Container& c) : m_container(&c)
{
m_size = 8*sizeof(Container);
m_index = 0;
}
explicit bit_iterator() : m_container(0)
{
m_size = 8*sizeof(Container);
m_index = m_size;
}
bool operator* ()
{
char mask = 1;
char* pc = (char*)m_container;
int i = (m_size-m_index-1)/8;
int off = (m_size-m_index-1)%8;
mask <<=off;
return pc[i] & mask;
}
bit_iterator<Container>& operator++()
{
m_index++;
return *this;
}
bit_iterator<Container>& operator++(int)
{
m_index++;
return *this;
}
bool operator==(bit_iterator<Container>& bitIt)
{
return m_index == bitIt.m_index;
}
bool operator!=(bit_iterator<Container>& bitIt)
{
return !(*this == bitIt);
}
protected:
Container* m_container;
private:
int m_size;
int m_index;
};
用该迭代器可以将任意类型对象以二进制格式输出:
double a = 10;
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));