std::ostream data-modifying manipulator?

  • Thread starter Steven T. Hatton
  • Start date
S

Steven T. Hatton

I tried to create my own manipulator that would both set the width of the
subsequent output field, and cast an unsigned char to unsigned in. I came
up with the following rather ugly hack. Notice that I am instantiating UI
before any call to out.operator<<(). Is there a better way to accomplish this?

What I'd like is something I could simply place in the output call between '<<'
operators without having to instantiate it first. The reason this is different
from a typical manipulator is because it is operating on the data as well as the
stream.

typedef unsigned char byte;

struct UI {
unsigned _w;
std::eek:stream* _out;
UI(unsigned w_=2)
:_w(w_)
{}
UI& setOut(std::eek:stream& out_){
_out = &out_;
return *this;
}
std::eek:stream& operator<<(byte b) { return *_out<<std::setw(_w)<<unsigned(b); }
};

UI& operator<<(std::eek:stream& out, UI& u) { return u.setOut(out); }

std::eek:stream& describe(std::eek:stream& out, const Identification_IF& subject ){
std::vector<byte> data(subject.getData());
std::ios::fmtflags savedFormat(out.flags());
UI ui;
return out
<<std::hex<<std::setfill('0')
<<"unsigned char Elf32_Ehdr::e_ident[EI_NIDENT]; EI_NIDENT = " << EI_NIDENT << "\n"
<<" [ 0] = "<<ui<<data[ 0]<<" EI_MAG0 : Always ELFMAG0 = '0x7f'\n"
<<" [ 1] = "<<ui<<data[ 1]<<" EI_MAG1 : Always ELFMAG1 = 'E' = "<<ui<<'E'<<"\n"
<<" [ 2] = "<<ui<<data[ 2]<<" EI_MAG2 : Always ELFMAG1 = 'L' = "<<ui<<'L'<<"\n"
<<" [ 3] = "<<ui<<data[ 3]<<" EI_MAG3 : Always ELFMAG1 = 'F' = "<<ui<<'F'<<"\n"
<<" [ 4] = "<<ui<<data[ 4]<<" EI_CLASS : ELFCLASSNONE = 0 | ELFCLASS32 = 1 | ELFCLASS64 = 2\n"
<<" [ 5] = "<<ui<<data[ 5]<<" EI_DATA : ELFDATANONE = 0 | ELFDATA2LSB = 1 | ELFDATA2MSB = 2\n"
<<" [ 6] = "<<ui<<data[ 6]<<" EI_VERSION : ELF version of the file\n"
<<" [ 7] = "<<ui<<data[ 7]<<" EI_PAD : end of ELF Identification data\n"
<<" [ 8] = "<<ui<<data[ 8]<<" Unused\n"
<<" [ 9] = "<<ui<<data[ 9]<<" Unused\n"
<<" [10] = "<<ui<<data[10]<<" Unused\n"
<<" [11] = "<<ui<<data[11]<<" Unused\n"
<<" [12] = "<<ui<<data[12]<<" Unused\n"
<<" [13] = "<<ui<<data[13]<<" Unused\n"
<<" [14] = "<<ui<<data[14]<<" Unused\n"
<<" [15] = "<<ui<<data[15]<<" Unused\n";
}
--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top