C++ custom stream manipulator that changes next it

2020-01-24 02:15发布

In C++, to print a number in hexadecimal you do this:

int num = 10;
std::cout << std::hex << num; // => 'a'

I know I can create a manipulator that just adds stuff to the stream like so:

std::ostream& windows_feed(std::ostream& out)
{
    out << "\r\n";
    return out;
}

std::cout << "Hello" << windows_feed; // => "Hello\r\n"

However, how can I create a manipulator that, like 'hex', modifies items to come on the stream? As a simple example, how would I create the plusone manipulator here?:

int num2 = 1;
std::cout << "1 + 1 = " << plusone << num2; // => "1 + 1 = 2"

// note that the value stored in num2 does not change, just its display above.
std::cout << num2; // => "1"

标签: c++ stream
7条回答
▲ chillily
2楼-- · 2020-01-24 02:55

The hex, dec and oct manipulators simply change the basefield property of the existing stream.

See C++ Reference for more deatail about these manipulators.

As posted in Neil Butterworth's answer, you would need to extend the existing stream classes, or create your own, in order to have manipulators that affect future values inserted into the stream.

In the example of your plusone manipulator, the stream object would have to have an internal flag to indicate that one should be added to all inserted values. The plusone manipulator would simply set that flag, and the code to handle stream insertion would check that flag before inserting numbers.

查看更多
登录 后发表回答