It is possible to modify the behavior of a stream with different options, for example:
std::cout << 0xfabadau << '\n';
std::cout << std::hex << std::setfill('0') << std::setw(8) << 0xfabadau << '\n';
Sample:
16431834 00fabada
Now suppose I have a custom type byte_buffer
:
using byte = std::uint8_t;
using byte_buffer = std::vector<byte>;
std::ostream &operator <<(std::ostream &o, const byte_buffer &buffer)
{
for (const auto &b : buffer) o << std::hex << int{b};
return o << std::dec;
}
When using it, I can not apply the custom format:
byte_buffer b { 0xfau, 0xbau, 0xdau, };
std::cout << b << '\n';
std::cout << std::hex << std::setfill('0') << std::setw(8) << b << '\n';
The previous code shows:
fabada 000000fabada
std::setfill
and std::setw
of outside of std::ostream &operator <<
has been applied to the first byte
of byte_buffer
within of std::ostream &operator <<
giving place to the format that we see. This is not unexpected, but it is not desired. The output you want is:
fabada 00fabada
How should I change the std::ostream &operator <<(std::ostream &o, const byte_buffer &buffer)
so that byte_buffer
behaves the way I expect?