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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With