Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ copy stream manipulator to other stream

Imagine a std::ostream& operator<< wants to do some stuff with numbers. For this purpose, someone might want to use std::hex, some other may want to use none, whatever, any manipulator is possible.

How could I copy those to another std::ostream without the text-content of the ostream passed as argument? I need the manipulators only.

So I want that std::cout << std::hex << someCoolClass(10), where someCoolClass could look like

struct someCoolClass
{
    someCoolClass(int i) : _i(i)
    {}

    friend std::ostream& operator<<(std::ostream& os, const someCoolClass& rhs)
    {
        std::stringstream ss;
        //magically copy manipulators of os
        ss << _i;
        return os << ss.str();
    }
private:
    int _i;
};

prints a. I know this example is useless and especially the other stream to convert the integer to a string seems to be useless but lets imagine that this isn't useless and not pure nonsene.

Thanks.

like image 933
NaCl Avatar asked Mar 19 '23 00:03

NaCl


1 Answers

ios::copyfmt

friend std::ostream& operator<<(std::ostream& os, const someCoolClass& rhs)
{
    std::stringstream ss;
    ss.copyfmt(os);        // <- copy formatting
    ss << rhs._i;
    return os << ss.str();
}

DEMO

like image 134
Piotr Skotnicki Avatar answered Mar 25 '23 07:03

Piotr Skotnicki