I am generating assembly and I want to have all the generated code aligned. This includes having sth like cout<<"\t"<<left<<setfill(' ')<< setw(8);
in front of each instruction. How can I declare an ostream modifier that will save me writing all this code at every line. I am looking for sth like:
ostream mod="\t"<<left<<setfill(' ')<< setw(8);
cout<<mod<<"addiu"<<"$sp, $sp, 24"<<endl;
I know I can do this with a macro, but I want to know how I can do it with ostream object.
Streaming a function that takes and returns a std::ostream&
will call that function on the stream. This is how some of the standard manipulators are defined, and is the quickest way to create your own, if they don't need to take any arguments:
namespace cds {
std::ostream& pad(std::ostream& os) {
return os << '\t' << std::setfill(' ') << std::setw(8);
}
}
int main() {
std::cout << cds::pad << "Hello" << '\n'
<< cds::pad << "World" << '\n';
}
prints:
$ ./SO
Hello
World
As pointed out in the comments, you don't really need to keep repeating the setfill
, but as you don't know (from the perspective of the author of the manipulator) what will be called on the stream in between, you may as well.
Also, as I explain here, many developers, myself included, consider use of endl
a bad practice.